问题描述
这是plunkr:http://plnkr.co/edit/CzcVzKSvpKJTuTKARVJz?p=preview
这是我的简单代码:
.directive('ngB', [function () {
return {
'restrict': 'A',
'scope': {
'ngB': '='
},
'link': function($scope, el) {
var clss = 'b'
, go = function () {
if ($scope.ngB) {
el.removeClass('a');
el.addClass(clss);
} else {
el.removeClass(clss);
}
};
$scope.$watch('ngB', function () {
go();
});
}
};
}])
.directive('ngF', [function () {
return {
'restrict': 'A',
'scope': {
'ngF': '='
},
'link': function($scope, el) {
var clss = 'f'
, go = function () {
if ($scope.ngF) {
el.removeClass('a');
el.addClass(clss);
} else {
el.removeClass(clss);
}
};
$scope.$watch('ngF', function () {
go();
});
}
};
}]);
//view.html
<span ng-b="2 > 1" ng-a="1 > 2">here</span>
它在控制台返回这个错误:https://docs.angularjs.org/error/$compile/multidir
It returns this error in console: https://docs.angularjs.org/error/$compile/multidir
如何在不从 elmeent 中删除指令之一的情况下解决此问题
How can i fix this without removing one of the directives from the elmeent
非常感谢.
推荐答案
如上所述,不能有两个指令在同一个元素上创建多个作用域,无论是隔离还是子作用域.
As suggested above, you cannot have two directives creating multiple scopes, whether isolate or child, on the same element.
您并不总是需要隔离范围.
You don't always need an isolate scope.
如果您所做的只是观察属性值的变化:
if all you are doing is observing a change in an attribute value:
<span ng-f="{{1 < foo}}"></span>
然后您可以使用 attrs.$observe
获取更改:
Then you could pick up the changes with attrs.$observe
:
link: function(scope, element, attrs){
attrs.$observe("ngF", function(v){
// do something
});
}
但是,如果您正在观察分配给属性或表达式结果的模型值的变化
If, however, you are watching for a change in the model value assigned to the attribute or an expression result
<span ng-f="foo"></span>
<span ng-f="foo === 10"></span>
在我看来是这样的,您可以使用 $parse
服务和 $watch 来更改值.
which seems to me to be the case, you can use $parse
service and $watch for changes in the value.
link: function(scope, element, attrs){
var parsed = $parse(attrs.ngF);
scope.$watch(function(){
return parsed(scope);
},
function(v){
// do something
});
}
这篇关于AngularJS 在同一元素上有多个指令,$compile:multidir ERROR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!