![](/img/trans.png)
[英]How do I dynamically add an AngularJS directive to an element conditionally?
[英]How do I dynamically access a property inside an angularjs directive?
當給定數組時,我有一個指令,它使用名稱作為復選框的標簽為該項目列表創建復選框。
HTML
<div>
<a style="float:right; margin-bottom: 5px;" ng-click="selectNone()" href="#">Select None</a>
<a style="float:right; margin-bottom: 5px;margin-left: 10px" ng-click="selectAll()" href="#">Select All</a>
<div class="cleared"></div>
<div class="form-input form-list">
<label ng-repeat="item in valuelist | orderBy:'Name'">
<input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}<br />
</label>
</div>
JS
'use strict';
growllApp.directive('checkboxlist', [function () {
return {
restrict: 'E',
templateUrl: 'scripts/modules/checkboxlist.template.html',
controller: 'checkboxlistController',
scope: {
model: "=",
value: "=",
valuelist: "="
}
}
}]);
growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
$scope.selectAll = function () {
$scope.model = angular.copy($scope.valuelist);
};
$scope.selectNone = function () {
$scope.model = [];
};
}]);
使用指令
<checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
所有這些在大多數情況下都可以正常工作。 但是,在一種情況下,我要傳遞的數組中的對象沒有屬性“名稱”,而是具有屬性“標題”。
如何使用我在名為“值”的指令中具有的屬性來確定標簽。
因此,在html指令中,而不是說{{item.Name}},在某些情況下如何通過傳遞屬性名稱為title來指定{{item.Title}}?
除了提示三元運算符的答案外,您還可以簡化為類似
{{ item.Name || item.Title }}
並且您可以根據需要選擇多種選擇。
但是,我認為,更健壯的方法是像其他人建議的那樣做
scope : {
...
key:'@'
...
}
其中key是屬性的名稱及其訪問方式
{{ item[key] }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.