作为一名新的 Angular 用户,我遇到了一个问题,即我无法在一个元素上使用具有隔离范围的多个指令。
我后来意识到,我可以在指令的链接方法上使用 attrs.$observe,而不是隔离范围,以保持属性值的最新状态。不过,我想确保我以正确的方式做事。
什么时候应该使用隔离作用域以及什么时候应该使用 attrs.$observe?例如...
隔离范围
App.directive('tooltip', function() {
return {
scope: {
tooltip: '@'
},
link: function(scope, element) {
element.enableSomeTooltip({
content: function() {
return scope.tooltip;
}
});
}
}
});
attrs.$observe()
App.directive('tooltip', function() {
return {
link: function(scope, element, attrs) {
var tooltip;
attrs.$observe('tooltip', function(newTooltip) {
tooltip = newTooltip;
});
element.enableSomeTooltip({
content: function() {
return tooltip;
}
});
}
}
});
以上两者的最终结果相同,对吧?那么这就是“正确”或“Angular ”的做事方式。如果他们没有相同的最终结果,请解释一下,以便我更好地理解。谢谢!
编辑:我想我还可以通过其他方式访问该属性,例如通过元素。例如。 element.attr('工具提示').然而,在这种特殊情况下,该属性包含一个需要解析的表达式,这就是我要查看上面两个选项的原因。
最佳答案
在制作需要将数据绑定(bind)到其 html 模板的可重用组件时,我倾向于使用隔离范围。
例如,如果指令仅调用一些非 Angular 插件(如 Bootstrap 或 JQueryUI)并且从不创建 html 模板,则创建隔离范围可能没有太多值(value),因为 attrs.$observe 可以抓取属性的更改值并将这些值保存到指令的链接闭包中,而无需触及 $scope。
HTML
<div ng-controller="MyController as vm">
<isolate-scope-directive message="vm.message"></isolate-scope-directive>
<non-isolate-scope-directive message="{{vm.message}}"></non-isolate-scope-directive>
</div>
JS
angular.module('app').controller('MyController', function ($scope) {
var vm = this;
vm.message = 'Hello world';
var i = 0;
setInterval(function () {
$scope.$apply(function () {
vm.message = 'Hello world ' + i++;
});
}, 500);
});
angular.module('app').directive('isolateScopeDirective', function () {
return {
scope: {
message: '='
},
link: function ($scope, element, attributes, controller) {},
template: '<div>{{message}}</div>'
};
});
angular.module('app').directive('nonIsolateScopeDirective', function () {
return {
link: function ($scope, element, attributes, controller) {
attributes.$observe('message', function(newMessage){
element.html(newMessage);
});
},
template: '<div></div>'
};
});
这是一个 jsfiddle,它显示了这一点:http://jsfiddle.net/ow02cv5w/2/
关于angularjs - 指令隔离范围与 attrs.$observe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957616/