我有这个 fiddle ,它显示了一个目前有警报的指令。还有一个具有警报功能的 Controller 。除了按钮上显示的文本绑定(bind)丢失之外,这一切都工作正常。有什么想法可以帮助我吗?
<div ng-app="directiveApp" ng-controller="MainController">
<button ng-click="doStuff()" unsaved-warning-trigger>
{{buttonText}}
</button>
</div>
var app = angular.module("directiveApp", []);
app.directive('unsavedWarningTrigger',
function() {
return {
priority: 1,
terminal: true,
link: function (scope, element, attr) {
var clickAction = attr.ngClick;
element.bind('click',function () {
if (window.confirm("Sure?")) {
scope.$eval(clickAction)
}
});
}
};
}
);
MainController = function($scope) {
$scope.buttonText = 'bound button';
$scope.doStuff = function () {
alert("doing stuff");
};
}
最佳答案
由于将“terminal”属性设置为“true”,您会发生这种情况。通过这样做,您可以防止稍后执行的任何其他指令(即使它们不明确)。
考虑一下您的要求以及是否真的需要设置
'terminal: true'
否则,您应该遵循不同的范围方法。
我附加了一个 jsFiddle,您可以通过删除该属性来查看绑定(bind)工作:
还有一篇关于终端和优先级属性的好文章:
How to understand the `terminal` of directive?
编辑:
但是,要实现您想要的全部功能,您可以将指令编写为:
app.directive('unsavedWarningTrigger',
function() {
return {
priority: 1,
terminal: true,
link: function (scope, element, attr) {
element.text(scope.buttonText);
var clickAction = attr.ngClick;
element.bind('click',function () {
if (window.confirm("Sure?")) {
scope.$eval(clickAction)
}
});
}
};
}
);
参见 jsFiddle:
请考虑到,通过此实现,按钮文本仅在指令链接时设置一次。由于与buttonText的绑定(bind)已被属性“terminal: true”破坏,如果您希望按钮文本在变量buttonText更改时更新,则需要为其设置$watch并执行element.text(scope .buttonText)在其中。
最好。
关于javascript - 失去指令的约束力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346932/