在下面的代码中,我试图在编译阶段添加一个按钮,并且指定了ng作为范围的方法。 在链接阶段,通过调试,我发现“compiledEle”包含按钮,那么ng-click也不会调用scope方法。作用域没有与在编译阶段添加的新元素相关
angular.module("app", [])
.controller("ctrl1", function($scope){
$scope.myModelObj = {
name: 'Ratnesh',
value: 100
};
})
.directive("dirOne",function($compile){
return {
restrict: 'E',
scope: {
myModel : "="
},
compile: function(ele){
ele.append("<button ng-click=\"showAlert()\">click ME</button>")
return {
post: function($scope, compiledEle){
$scope.showAlert = function(){
alert("The button is clicked");
};
}
};
}
};
});
可能是什么,该范围的方法不会被绑定到在编译阶段添加的按钮,但同样可以在模板/ templateUrl进行绑定,如果我按钮的原因。此外该方法获得绑定如果链接阶段,我们有一句台词:
$编译(compiledEle.contents())($范围);)
也将是获得绑定到方法,而不是在链接阶段添加“$ scope.showAlert”,我们已经在控制器中的方法!
.controller("ctrl1", function($scope){
$scope.myModelObj = {
name: 'Ratnesh',
value: 100
};
$scope.showAlert = function(){
alert("The button is clicked");
};
})
编译方法是做DOM操作和链接阶段是将编译后的html链接到范围。所以我们可以在编译期间向DOM添加新的元素,在链接阶段添加新的范围方法,那么我的期望会出现什么问题呢?
尝试在预编译时附加它 – charlietfl
尝试了前后两者,结果相同。 –