[英]Optional expression attribute in AngularJS directive
我有一個自定義導航指令需要一個可選的“禁用”屬性,我不確定它是否可能。
在我的主控制器中:
.controller('NavCtrl', ['UserResource','RoleResource'], function(UserResource,RoleResource){
var user = UserResource.getUser();
var roles = RoleResource.getRoles();
UserService.init(user, roles); //????
});
在我的指令中:
.directive('navItem', function(){
return{
restrict: 'A',
scope: {
text: '@',
href: '@',
id: '@',
disable: '&'
},
controller: function($scope, $element, $attrs){
$scope.disabled = ''; //Not sure I even need a controller here
},
replace: true,
link: function(scope, element, attrs){
scope.$eval(attrs.disable);
},
template: '<li class="{{disabled}}"><a href="{{href}}" id="{{id}}">{{text}}</a></li>'
}
});
在我的HTML中,我想做這樣的事情:
<div data-nav-item text="My Text" href="/mytemplate.html" id="idx"
disable="UserService.hasRole('ADMIN,BILLING') && someOtherFn(xxx) || ...">
你可以通過chaning $ eval來調用你的工作
scope.$parent.$eval(attrs.disable);
因為您需要評估父范圍中attrs.disable
中包含的表達式,而不是指令的隔離范圍。 但是,由於您使用的是'&'語法,它將自動評估父作用域中的表達式。 所以,請執行以下操作:
if(angular.isDefined(attrs.disable)) {
scope.disable();
}
小提琴 。
做同樣事情的一種方法就是這個http://jsfiddle.net/fFsRr/7 。
您可以將todisableornot="rights[1]"
替換為您的表達式,如todisableornot="UserService.hasRole('ADMIN,BILLING') && someOtherFn(xxx) || ..."
。
現在正如Mark Rajcok所說,只要您調用該屬性,就會在父范圍內評估屬性todisableornot
。 所以
<li ng-class="{adminRole:todisableornot()}"><a href="{{href}}" id="{{id}}">{{text}}</a></li>
如果todisableornot
屬性的計算結果為true(在父作用域的上下文中),則將應用類adminRole
。
您可以通過更改$scope.rights =[true, false];
來測試這個$scope.rights =[true, false];
針對此特定問題的更合適的實現是對可從復雜語句指定其值的簡單模型屬性進行可選綁定。 Angular文檔反復提到最佳實踐是綁定到模型屬性而不是函數。 指令的“&”綁定主要用於實現回調,您需要將數據從指令傳遞到其父級。
實現可選綁定如下所示:
碼:
angular.module("testApp", [])
.controller("testCtrl", ["$scope", function testCtrl($scope) {
$scope.myFlag = false;
}])
.directive("testDir", function testDir() {
return {
restrict: "EA",
scope: {
identity: "@",
optional: "=?"
},
link: function testDirLink($scope, $element, $attrs) {
if (typeof $scope.optional == "undefined") {
$scope.description = "optional was undefined";
}
else {
$scope.description = "optional = '" + $scope.optional + "'";
}
},
template: "<div>{{identity}} - {{description}}</div>"
};
});
HTML:
<div ng-app="testApp" ng-controller="testCtrl">
<test-dir identity="one" optional="myFlag"></test-dir>
<test-dir identity="two"></test-dir>
</div>
小提琴: http : //jsfiddle.net/YHqLk/
最近我遇到了這個問題,發現我在index.html中有多個指令文件的引用(腳本標記)。 一旦我刪除了這些額外的引用,問題就消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.