我正在尝试使用 Angularjs 创建一个应用程序,这是一个相当大的应用程序,需要分解为多个 Controller 。我需要跨 Controller 进行计算。
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>
请找到我的Plunk在这里。
我想将 child 的费用和家庭的费用添加到结果 Controller 的“Result.Expense”
最佳答案
将所有内容放入服务中,并调用该服务来获取所有内容。
编辑:请参阅更新的plnk 。综上所述,当服务发生变化时,您现在需要通知 Controller 。看我的回答here关于将观察者模式与 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();
});
关于javascript - Angularjs - 跨 Controller 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804181/