我有一个 javascript 函数,它从 JSON 数据构建树并创建 anchor 标记元素列表,例如:
<a ng-click="shareParent(4619)">Some data</a>
此列表在页面加载后填充。此 ng-click 未在 Controller 上注册。这是我的 Controller :
catalog.controller('categoryTree', ['$scope',function($scope) {
$scope.shareParent = function(parent) {
console.log(parent)
}
}]);
数据永远不会出现在 Controller 上。我是新手,所以我可能在这里做错了。我什至试过调用 $scope.$apply(),但这也没有任何用处。
anchor 元素确实有一个 Controller 与之关联,并且还声明了一个 ng-app。只是 ng-click 不起作用。
编辑:
在附加 DOM 元素后,在我的 Controller 中使用以下注入(inject)器代码解决了这个问题:
$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);
});
可能有更好的方法。
最佳答案
当你在 Angular 中创建新的 HTML 元素时,你必须将它连接到一个范围。这称为编译
例如:
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!')
}
}
关于javascript - 当通过另一个 javascript 函数加载 HTML 时,Angular JS ng-click 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36004855/