我想调用一个函数,每次在Angular Js中调用另一个函数。
在下面的代码中,每次调用checkAll()或uncheckAll时,我都希望调用函数checkTotal()。虽然我已经以正常的js方式添加它,但它似乎没有用。当我直接在点击动作中调用它时,它正在工作。
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl', function($scope) {
$scope.roles = [
{id: 1, text: 'WebDesign' , cost: 10},
{id: 2, text: 'Photoshop' , cost: 20},
{id: 3, text: 'Design' , cost: 30},
{id: 4, text: 'Branding' , cost: 15}
];
$scope.user = {
roles: [2, 4]
};
console.log($scope.roles);
$scope.checkAll = function() {
$scope.user.roles = $scope.roles.map(function(item) { return item.id; });
checkTotal()
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
checkTotal();
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push(1);
checkTotal();
};
$scope.checkTotal = function() {
$scope.user.total = $scope.roles.map(function(item) { return item.cost; });
var arr = $scope.user.total;
var total=0;
for(var i in arr) { total += arr[i]; }
$scope.user.caltotal = total;
};
});
我的Html
<div ng-app="app" ng-controller="Ctrl">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}} | {{role.cost}}
</label>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="checkFirst()">check first</button>
<button ng-click="checkTotal()">Total</button>
<br><br>
user.roles {{ user.roles | json }} <br>
Total: {{ user.caltotal }}
</div>
我已全部实施in a Fiddle.
答案 0 :(得分:1)
尝试添加$ scope对象,如下所示:
$scope.checkTotal();