首页 > 代码库 > angular中不同controller传值问题 以及应用实例

angular中不同controller传值问题 以及应用实例

参考

http://www.cnblogs.com/hardi/p/5232776.html

http://www.codesec.net/view/168790.html

 1 var myApp = angular.module("myApp", []);
 2 myApp.factory(‘Data‘, function() {
 3   return {
 4     name: "Ting"
 5   }
 6 });
 7 
 8 myApp.controller(‘FirstCtrl‘, function($scope, Data) {
 9   $scope.data =http://www.mamicode.com/ Data;
10   $scope.setName = function() {
11     Data.name = "Jack";
12   }
13 });
14 
15 myApp.controller(‘SecondCtrl‘, function($scope, Data) {
16   $scope.data =http://www.mamicode.com/ Data;
17   $scope.setName = function() {
18     Data.name = "Moby";
19   }
20 });

现在遇到的一个场景是:添加和修改对象的唯一属性,由于两个功能分属不同的控制器,设计如下:

 1 // service
 2 myControllers.factory(‘factoryData‘, function() {
 3   return {
 4     flag: false
 5   }
 6 });
 7 
 8 // 添加操作
 9 myControllers.controller(‘addCtrl‘, [‘$scope‘, ‘$rootScope‘, ‘$http‘, ‘factoryData‘,
10     function($scope, $rootScope, $http, factoryData) {
11         $scope.myList = [];
12         // get myList from back stage ...
13         
14         $scope.dupNameCheck = function(nameStr) {
15             var myList = $scope.myList;
16             var obj;
17             for(index in myList) {
18                 obj = myList[index];
19                 if(obj.name == nameStr) {
20                     factoryData.flag = false;
21                 } else {
22                     factoryData.flag = true;
23                 }
24             }
25            }    
26     }
27 ]);
28 
29 // 编辑和提交
30 myControllers.controller(‘editCtrl‘, [‘$scope‘, ‘$rootScope‘, ‘$http‘, ‘factoryData‘,
31     function($scope, $rootScope, $http, factoryData) {
32         $scope.myList = [];
33         $scope.mySubmit = function() {
34             if(!factoryData.flag) {
35                 alert("名称重复!");
36                 return false;
37             } else {
38                 // do submit to back stage ...
39             }
40            }    
41     }
42 ]);

 

angular中不同controller传值问题 以及应用实例