简体   繁体   English

当通过另一个javascript函数加载HTML时,Angular JS ng-click不起作用

[英]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: 我有一个javascript函数,它从JSON数据构建一个树,并创建一个锚标记元素列表,如:

<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. 此ng-click未在控制器中注册。 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. 我甚至尝试过调用$ scope。$ apply(),但这也没有任何好处。

The anchor element does have a controller associated with it and an ng-app is also declared. anchor元素确实有一个与之关联的控制器,并且还声明了ng-app。 Just the ng-click isn't working. 只是ng-click不起作用。


EDIT: 编辑:

Solved it using the following injector code in my controller after the DOM element was appended: 添加DOM元素后,在我的控制器中使用以下注入器代码解决它:

$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. 可能有更好的方法来做到这一点。

When you create new HTML elements in Angular, you have to connect it to a scope. 在Angular中创建新的HTML元素时,必须将其连接到范围。 This is called compiling 这称为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 更多信息: Angular $ compile服务

just try using $compile() ($scope) 只是尝试使用$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. 然后你需要将DOM元素附加到你的页面。

Hope this helps. 希望这可以帮助。

Your code looks quite okay. 你的代码看起来很好。 Have you bind the HTML to your controller categoryTree ? 您是否将HTML绑定到控制器categoryTree

我建议使用简单的onclick和访问函数和变量通过angular element().....玩得开心;)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM