我有一个在我的控制器中不断重复的功能。 它看起来像这样:
//FUNCTION 1
$scope.selectedage = [];
$scope.pushage = function (age) {
age.chosen = true;
$scope.selectedage.push(age);
console.log($scope.selectedage);
};
$scope.unpushage = function (age) {
age.chosen = false;
var index=$scope.selectedage.indexOf(age)
$scope.selectedage.splice(index,1);
console.log($scope.selectedage);
}
//FUNCTION 2
$scope.selectedgender = [];
$scope.pushgender = function (gender) {
gender.chosen = true;
$scope.selectedgender.push(gender);
console.log($scope.selectedgender);
};
$scope.unpushgender = function (gender) {
gender.chosen = false;
var index=$scope.selectedgender.indexOf(gender)
$scope.selectedgender.splice(index,1);
console.log($scope.selectedgender);
}
对于8个不同的数组,我有8次。
有没有办法写一次并重复使用它只是改变一些值?
答案 0 :(得分:2)
您可以创建一个接受值(容器)的通用函数,它需要在其中写入"值"。像:
$scope.push = function(container, value){
value.chosen = true;
container.push(value);
console.log(container);
}
$scope.unpush = function(container, value){
value.chosen = false;
var index = container.indexOf(value)
container.splice(index, 1);
console.log(container);
}
//sample
$scope.push($scope.selectedage, 10);
$scope.push($scope.selectedgender, "Male");
答案 1 :(得分:1)
function togglePushStatusOfItem(item, itemKey, chosenStatus){
item.status = chosenStatus;
if(chosenStatus == true){
$scope[itemKey].push(item);
} else {
var index=$scope[itemKey].indexOf(item)
$scope[itemKey].splice(index,1);
}
console.log($scope[itemKey]);
}
togglePushStatusOfItem(user, 'selectedAge',true);
重构要在服务中重用的代码
(function() {
'use strict';
angular
.module('myApp')
.factory('ItemFactory', ItemFactory);
ItemFactory.$inject = [];
/* @ngInject */
function ItemFactory() {
var service = {
toggleItemStatus: toggleItemStatus
};
return service;
////////////////
/*
itemContainer - equivalent to scope
item - item to replace or push
itemKey - itemKey
chosenStatus - true to push and false to remove
*/
function toggleItemStatus(itemContainer, item, itemKey, chosenStatus) {
item.status = chosenStatus;
if (chosenStatus == true) {
itemContainer[itemKey].push(item);
} else {
var index = $scope[itemKey].indexOf(item)
itemContainer[itemKey].splice(index, 1);
}
console.log(itemContainer[itemKey]);
}
}
})();
在您的控制器中,您可以像这样使用它
ItemFactory.toggleItemStatus($scope, item, 'selectedAge', true);// to push item
ItemFactory.toggleItemStatus($scope, item, 'selectedAge', false);// to remove item
我唯一的区别是我使用相同的功能推送和取消项目。我希望这不会让你感到困惑。