Angular JS ng-click not working when HTML loaded through another javascript function

Viewed 1160

I have a javascript function that builds a tree from JSON data and creates a list of anchor tag elements like:

<a ng-click="shareParent(4619)">Some data</a>

This list is populated after the page is loaded. This ng-click doesn't get registered at the controller. Here is my controller:

catalog.controller('categoryTree', ['$scope',function($scope) {
    $scope.shareParent = function(parent) {
        console.log(parent)
      }
}]);

The data never shows up at the controller. I am a newbie, so I may be doing something really wrong here. I've even tried calling $scope.$apply(), but that doesn't do any good either.

The anchor element does have a controller associated with it and an ng-app is also declared. Just the ng-click isn't working.


EDIT:

Solved it using the following injector code in my controller after the DOM element was appended:

$injector = angular.element(document.querySelector('#categoryTree')).injector();
element = angular.element(document.querySelector('#category-tree'));
$injector.invoke(function ($compile) {
      var scope = element.scope();
      $compile(element)(scope);
   });

There may be a better way of doing this.

4 Answers
Related