ishaan
ishaan

Reputation: 2031

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

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.

Upvotes: 3

Views: 1208

Answers (4)

Talha
Talha

Reputation: 1636

I would recommend to use the simple on onclick and access functions and variables via angular element() ..... have fun ;)

angular.element(angular_app_controller_element).scope().var/function()

Upvotes: 0

Shankar D
Shankar D

Reputation: 94

just try using $compile() ($scope)

something like

var domElement = $compile('your javascript to create dom elements')($scope);

and then you will need to append the DOM element to your page.

Hope this helps.

Upvotes: 2

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24600

When you create new HTML elements in Angular, you have to connect it to a scope. This is called compiling

For example:

function myController($scope,$compile,$element){

  //Creating New Element
  var newElement=$('<div ng-click=hello()>Hello World</div>')

  //Compile The Element, and assign it to current scope
  $compile(newElement)($scope)

  //Append the element, to wherever do you want. For example to current controller element
  newElement.appendTo($element)

  $scope.hello=function(){
     alert('It is working!')
  }
}

More Info: Angular $compile service

Upvotes: 4

stanleyxu2005
stanleyxu2005

Reputation: 8241

Your code looks quite okay. Have you bind the HTML to your controller categoryTree?

Upvotes: 1

Related Questions