AngularJS遵守指令属性的表达,继承范围动态
我的代码是非常简单的:AngularJS遵守指令属性的表达,继承范围动态
.controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
$timeout(function() {
$scope.x = 5;
}, 2000);
}])
.directive('ngHey', ['$parse', function ($parse) {
return {
'restrict': 'A',
'scope': true,
'link': function($scope, el, atr) {
var go = function() {
if ($parse(atr.ngHey)()) {
alert('oiiiiiii');
}
};
atr.$observe('ngHey', function (val) {
if (val) {
go();
}
});
}
};
}]);
//view.html
<div ng-controller="Ctrl">
<span ng-hey="x > 3"></span>
</div>
我希望能够火的时候,指令表达的变化和当它是真的或假的,但目前的警报从来没有发生......
它的工作原理只有当我做这样的事情:
<div ng-controller="Ctrl">
<span ng-hey="{{x > 3}}"></span>
</div>
这是不是我要什么,我想指令执行的表达式为NG-IF或NG-隐藏等等
任何提示或帮助表示赞赏,感谢
在这种情况下,您不能使用$observe
,因为它Observes an interpolated attribute.
(documentation)。在这种情况下,你可以在这样的范围内使用$watch
:
.directive('ngHey', ['$parse',
function($parse) {
return {
scope: true,
link: function($scope, el, atr) {
var go = function(value) {
if (value) {
alert('oiiiiiii');
}
};
$scope.$watch(atr.ngHey, function(val) {
if (val) {
go(val);
}
});
}
};
}
]);
演示:http://plnkr.co/edit/XakjA2I7lpJdo9YAZFEH?p=preview
UPD。基于业务方案的意见,更新的指令看起来像:
.directive('ngHey', ['$parse',
function($parse) {
return {
scope:{ngHey: '='},
link: function($scope, el, atr) {
var go = function(value) {
if ($scope.ngHey) {
alert('oiiiiiii');
}
};
$scope.$watch('ngHey', function(val) {
if (val) {
go();
}
});
}
};
}
]);
注意,你怎么能在这种情况下使用$scope.ngHey
,不需要$eval
属性。
由于$timeout
稍后设置x的值,因此检查属性的指令内部的条件总是返回false
。因此,每当x
更改时,请使用$watch
检查go()
中的条件。
var myApp = angular.module('myApp',[]);
myApp.directive('ngHey', function() {
return {
'restrict': 'A',
'scope': true,
'link': function($scope, el, attr) {
var go = function() {
if ($scope.$eval(attr.ngHey)) {
alert('oiiiiiii');
}
};
$scope.$watch('x', function (val) {
if (val) {
go();
}
});
}
};
});
代替$parse
使用$scope.$eval
也同样,而不是$observe
使用$watch
。
对不起,但我不能使用$ watch,范围变量是动态/未知的,并不总是scope.x它可以是任何你想要/需要:) – sbaaaang 2015-03-03 13:11:07
范围$的eval(atr.ngHey) – mohamedrias 2015-03-03 11:30:34
@mohamedrias试过了,刚刚更换$范围$的eval(atr.ngHey)();在$ parse(atr.ngHey);但是当表达式变为真时,它似乎没有被触发 – sbaaaang 2015-03-03 11:41:18
我已经更新了答案。请检查:) – mohamedrias 2015-03-03 11:49:28