这是这个问题的后续。我有相同的设置:
Angular scope is shared for all modules and controllers
根模块、 Controller 和指令。现在回答问题:
我有一个服务,里面写着这样的内容:
firstModule.factory("firstService", function () {
return {
$('.mainitems').click(function () {
alert("hi")
});
};
});
还有一个指令,嵌套在其他指令中:
secondModule.directive("secondDirective", function () {
return {
templateUrl: "./myurl",
restrict: "E",
replace: true,
compile: function (tElement, tAttrs, controller) {
return {
}
}
}
});
当我有这样一行:restrict: "E"
时,点击功能不起作用,但是当我删除它时,它就起作用了。
知道为什么这可能是问题吗?奇怪的是,经过一天的调试,我发现了这个问题。
最佳答案
事实上,在工厂中管理 dom 操作是一个糟糕的模式!所有 DOM 操作都必须放在指令中,因此对于单击,它是 ng-click
例如:
<div ng-controller="MyController">
<div ng-click="click()"></div>
</div>
其中 click() 是您范围内的函数。所以你的 Controller 是这样的:
secondModule.controller('MyController', function($scope){
$scope.click = function(){
//do what you want
};
});
当您点击 div 时,它将调用 Controller 中的 click 函数
你的指令应该是:
secondModule.directive("secondDirective", function () {
return {
template: "<div ng-click='click()'><a>Click here</a></div>",
restrict: "E",
replace: true,
link: function (tElement, tAttrs, controller) {
}
}
});
你的 html 是这样的:
<second-directive></second-directive>
关于javascript - Angular 指令限制 E 破坏代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19006947/