我的指令有一个模板,其中包含一个名为 content
的范围变量:
<div class="directive-view">
<span class="directive-header">My Directive</span>
<span ng-bind-html="content"></span>
</div>
我有以下指令,它监视 content
的更改,然后编译元素的内容:
(function () {
"use strict";
angular
.module('myApp.myDirective', [])
.directive("myDirective", myDirective);
function myDirective($compile, $sce) {
return {
restrict: 'E',
scope: {
},
templateUrl:'../partials/directives/my-directive.html',
controller: function($scope) {
$scope.testAlert = function(msg) { alert(msg) };
},
link: function (scope, element, attrs, ctrl) {
scope.content = $sce.trustAsHtml('Initial value');
scope.$watch(attrs.content, function(value) {
element.html(value);
console.log("Content changed -- recompiling");
$compile(element.contents())(scope);
});
scope.content = $sce.trustAsHtml('<button ng-click="testAlert(\'clicked!\')">Click</button>');
}
};
}
})();
该指令呈现 button
元素。但是,当单击 button
元素时,不会调用 Controller 函数 testAlert()
。
此外,在将 content
设置为初始值
之后,$watch
回调仅调用一次。按钮设置content
后不会触发回调。 (我本以为当attrs.content
的值改变时会触发回调。)
如果我手动重新编译元素:
$compile(element.contents())(scope);
单击 button
元素时仍然不会触发 testAlert
函数。
如何正确地重新编译元素内容,以便进行正确的绑定(bind)?
最佳答案
在这种情况下,您不需要使用 $sce
。仅使用 $compile
。
jsfiddle 上的实例.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.name = 'Superhero';
$scope.changeTEmplate = function(){
$scope.cont = '<div><b>i\'m changed</b></div>';
}
})
.directive("myDirective", function myDirective($compile) {
return {
restrict: 'E',
scope: {content:"="},
template: `<div class="directive-view">
<span class="directive-header">My Directive</span>
<span></span>
</div>`,
controller: function($scope) {
$scope.testAlert = function(msg) {
alert(msg)
};
},
link: function(scope, element, attrs, ctrl) {
scope.$watch('content', function(value) {
var span = angular.element(element.find('span')[1]);
span.html(value);
console.log("Content changed -- recompiling",value);
$compile(span)(scope);
});
scope.content = '<button ng-click="testAlert(\'clicked!\')">Click</button>';
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Hello, {{name}}!
<button ng-click="changeTEmplate()"> change Content</button>
<my-directive content="cont"></my-directive>
</div>
</div>
关于javascript - AngularJS ng-click 在编译尝试后未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812572/