我需要在我的网站上显示列出产品和其他项目的复选框列表。 checklist-model 属性指令对此很有效,因为我可以将其绑定(bind)到与所选项目相关的项目列表。
当我简单地在我的 Angular Controller 中使用此代码时,所有这些都可以正常工作。但是,我有几个列表框需要以相同的方式显示,每个列表都使用相同的“全选”和“全选”按钮。我不想重复此代码和布局,因此我为整个列表创建了自己的指令。
问题是,当我使用自己的指令时,它无法正确绑定(bind)回我的数据,全选仅有效一次,全选根本不起作用。
我怀疑这与我传递范围的方式有关,并且这两个指令不能很好地协同工作。
为什么这在指令中不起作用?
这是一个jsfiddle:https://jsfiddle.net/fande455/m9qhnr9c/7/
HTML
<section ng-app="myApp" ng-controller="couponEditController">
<script type="text/ng-template" id="checkboxlist.template.html">
<div>
<div class="form-input form-list">
<label ng-repeat="item in valuelist | orderBy:value">
<input type="checkbox" checklist-model="model" checklist-value="item" /> {{item[value]}}
<br />
</label>
</div>
<button class="btn btn-default" style="float:left; margin-bottom: 5px;margin-left: 10px;margin-right:10px" ng-click="selectNone()">Select None</button>
<button class="btn btn-default" style="float:left; margin-bottom: 5px;" ng-click="selectAll()">Select All</button>
<div class="cleared"></div>
</div>
</script>
<div>
<checkboxlist model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</div>
</section>
JS
var myApp = angular.module('myApp', ['checklist-model']);
myApp.directive('checkboxlist', [function() {
return {
restrict: 'E',
templateUrl: 'checkboxlist.template.html',
controller: 'checkboxlistController',
scope: {
model: "=",
value: "@",
valuelist: "="
},
require: '^checklist-model'
}
}]);
myApp.controller('checkboxlistController', ['$scope', function($scope) {
$scope.selectAll = function() {
$scope.model = angular.copy($scope.valuelist);
};
$scope.selectNone = function() {
$scope.model = [];
};
}]);
myApp.controller('couponEditController', ['$scope', function($scope) {
$scope.coupon =
{"Id": 1,
"Name": "My Coupon",
"Products": []
}
;
$scope.productsList = [{
"Id": 1,
"Name": "Product 1"
}, {
"Id": 2,
"Name": "Product 2"
}];
}]);
最佳答案
来自文档:
Instead of doing checklistModelList = [] it is better to do checklistModelList.splice(0, checklistModelList.length)
在你的代码中你应该这样做
$scope.selectAll = function() {
$scope.selectNone();
$scope.model.push.apply($scope.model, $scope.valuelist);
};
$scope.selectNone = function() {
$scope.model.length = 0;
};
这是更新后的 fiddle :https://jsfiddle.net/m9qhnr9c/9/
这个想法不是用新数组替换数组,而是仅修改其元素。
关于javascript - 如何在 AngularJS 的元素指令模板内使用属性指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122869/