javascript - Angularjs - Cross Controller Calculation -
i trying create application angularjs, it's large application needs broken down multiple controllers. need calculate across controllers.
angular.module('cross.controller.demo',[]); angular.module('cross.controller.demo').controller('kidsctrl', function ($scope) { $scope.kids = [ {"name":"john", "expense":"1000"}, {"name":"anna", "expense":"900"}]; }); angular.module('cross.controller.demo').controller('housectrl', function ($scope) { $scope.house = {"category":"utilities", "expense":"2000"}; }); angular.module('cross.controller.demo').controller('resultctrl', function ($scope) { $scope.result = {"category":"total", "expense":"2000"}; });
<!doctype html> <html ng-app="cross.controller.demo"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src="script.js"></script> <body> <div ng-controller="kidsctrl"> <div ng-repeat="kid in kids"> {{kid.name}} <input type="text" ng-model="kid.expense"> </div> </div> <div ng-controller="housectrl"> {{house.category}} <input type="text" ng-model="house.expense"> </div> <div ng-controller="resultctrl"> {{result.category}} <input type="text" ng-model="result.expense"> </div> </body> </html>
please find plunk here.
i want add both expenses kids , expense house result controller's "result.expense"
put service , call out service everything.
edit: see updated plnk. said, need notify controllers when these change in service. see answer here on using observer pattern service in angular.
angular.module('cross.controller.demo',[]); angular.module('cross.controller.demo').factory('sharedfactory', function() { var kids = [ {"name":"john", "expense":"1000"}, {"name":"anna", "expense":"900"}]; var house = {"category":"utilities", "expense":"2000"}; var gethouse = function() { return house; } var getkids = function() { return kids; } var gettotalexpenses = function() { var expenses = parseint(house.expense); kids.foreach(function(kid) { expenses += parseint(kid.expense); }); return { category: "total", expense: expenses } } return { gethouse: gethouse, getkids: getkids, gettotalexpenses: gettotalexpenses } }); angular.module('cross.controller.demo').controller('kidsctrl', function ($scope, sharedfactory) { $scope.kids = sharedfactory.getkids(); }); angular.module('cross.controller.demo').controller('housectrl', function ($scope, sharedfactory) { $scope.house = sharedfactory.gethouse(); }); angular.module('cross.controller.demo').controller('resultctrl', function ($scope, sharedfactory) { $scope.result = sharedfactory.gettotalexpenses(); });
Comments
Post a Comment