Question

I want to invoke a function, each time another function is invoked in Angular Js.

In the below code, each time checkAll() or uncheckAll is called, I want the function checkTotal() also to be called. Though I have added it in normal js way, it doesnt seem to work. When I call it from directly in a click action its working.

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;    

  };


});

My 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>

I have it all implemented in a Fiddle.

Was it helpful?

Solution

Try to add the $scope object like this:

$scope.checkTotal();  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top