[英]Where should I write general purpose controller function in angular.js?
我正在編寫一些用於檢查/取消選中表列表的函數,並且工作正常,
控制器是
invoiceApp.controller('itemController', ['$scope', 'itemService', '$route', function ($scope, itemService, $route) {
$scope.checkAllItem;
$scope.listItem = {
selected: []
};
$scope.checkUncheck = function () {
if ($scope.checkAllItem) {
$scope.listItem.selected = $scope.items.map(function (item) {
return item.id;
});
} else {
$scope.listItem.selected = [];
}
};
HTML表格,
<table id="dt_basic" class="table table-bordered table-hover" width="100%">
<thead>
<tr>
<th class="text-center" width="5%">
<input type="checkbox" name="checkbox-inline" ng-model="checkAllItem" ng-click="checkUncheck()">
<input type="checkbox" name="checkbox-inline" ng-click="uncheckAll()">
</th>
<th width="15%" ng-click="sort()">Name<a href="javascript:void(0)"><i class="fa fa-sort small"></i></a></th>
<th width="65%">Description</th>
<th width="5%">Unit</th>
<th width="10%">Rate</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items" data-toggle="modal" data-target="#itemModel" ng-click="getItem(item.id)" style="cursor: pointer">
<td class="text-center">
<input type="checkbox" checklist-model="listItem.selected" checklist-value="item.id">
</td>
<td><a>{{item.name}}</a></td>
<td>{{item.description}}</td>
<td>{{item.unit}}</td>
<td>{{item.rate}}</td>
</tr>
</tbody>
</table>
它工作正常,這是我的問題,在我的項目中,我在不同的頁面中有很多表,我不得不將過去的同一代碼(僅談論控制器)復制到任何地方。通常有什么方法可以編寫它嗎?
我嘗試了$routescope
,但是它不能與ng-model
一起使用,是否有任何方法可以實現相同的功能?
您可以將其轉變為服務,然后將服務注入到控制器需要的任何地方。 現在,您還可以包括用於處理數據的其他常用功能。 看到,
http://jsbin.com/madapaqoso/1/edit
app.factory("toolService", function(){
return {
checkUncheck: function(listItem) {
listItem.selected = [];
}
}
});
我沒有添加您的函數所增加的復雜性,但是您明白了。
或者,使用指令。 我也在jsbin中顯示了它。 但是,我更喜歡服務,因為服務是為管理數據而設計的,而指令則更關注DOM編輯和綁定$ watchers / events等。或者您可以將數據與服務保持一致,然后使用自定義指令來處理所有在桌子上的點擊。
我寫了一個自定義指令
invoiceApp.directive('checkUncheck', function () {
return {
restrict: 'E',
replace: true,
template: '<input type="checkbox" name="checkbox-inline" ng-model="checkAllItem" ng-click="checkUncheck()">',
link: function (scope) {
//check/uncheck and delete
scope.checkAllItem;
scope.listItem = {
selected: []
};
scope.checkUncheck = function () {
if (scope.checkAllItem) {
scope.listItem.selected = scope.items.map(function (item) {
return item.id;
});
} else {
scope.listItem.selected = [];
}
};
}
};
});
在HTML中,
<check-uncheck></check-uncheck>
現在,我可以與項目中的大多數表視圖共享checkUncheck函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.