angularjs在控制器之间共享数据configuration

我想知道什么是控制器之间共享指令的好方法。 我有两个不同的configuration使用不同的控制器的指令,第一个想到我想使用像:

//html <body data-ng-controller="MainCtrl"> <div class="container"> <div data-ui-view></div> </div> </body> //js .controller('MainCtrl', function ($scope,$upload) { /*File upload config*/ $scope.onFileSelect = function($files) { for (var i = 0; i < $files.length; i++) { var file = $files[i]; $scope.upload = $upload.upload({ url: 'server/upload/url', method: 'POST', data: {myObj: $scope.myModelObj}, file: file, }).progress(function(evt) { console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total)); }).success(function(data, status, headers, config) { console.log(data); }); } }; /* Datepicker config */ $scope.showWeeks = true; $scope.minDate = new Date(); $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { 'year-format': "'yy'", 'starting-day': 1 }; $scope.format = 'MMM d, yyyy'; }) .controller('IndexCtrl', function ($scope) { }) 

这样做我可以在我的孩子控制器中使用所有的function,但是我不太喜欢碰撞问题。 由于你不能使用服务(你不能在服务中使用$ scope),所以其他的select可以做一个其他的指令或者把代码放在一个运行块中,但是使用父控制器是完全相同的,所以你怎么看?

UPDATE

你怎么看待这个方法?

 //outside of angular stauff function MyTest(){ this.testScope = function(){ console.log('It works'); } } //inside a controller $scope.ns = new MyTest(); //in the view <p ng-click="ns.testScope()">ppp</p> 

RIUPDATE这似乎是最好的select:)

 MyTest.call($scope); 

考虑这篇文章描述的方法: 使用Mixin模式扩展AngularJS控制器

不要将你的方法从服务中拷贝出来,而要创build一个包含这些方法的基础控制器,然后在派生控制器上调用extend来混合它们。下面的例子:

 function AnimalController($scope, vocalization, color, runSpeed) { var _this = this; // Mixin instance properties. this.vocalization = vocalization; this.runSpeed = runSpeed; // Mixin instance methods. this.vocalize = function () { console.log(this.vocalization); }; // Mixin scope properties. $scope.color = color; // Mixin scope methods. $scope.run = function(){ console.log("run speed: " + _this.runSpeed ); }; } 

现在我们可以将AnimalController混入DogController中:

 function DogController($scope) { var _this = this; // Mixin Animal functionality into Dog. angular.extend(this, new AnimalController($scope, 'BARK BARK!', 'solid black', '35mph')); $scope.bark = function () { _this.vocalize(); // inherited from mixin. } } 

然后在我们的模板中使用DogController:

 <section ng-controller="DogController"> <p>Dog</p> <!-- Scope property mixin, displays: 'color: solid black' --> <p ng-bind-template="color: {{ color }}"></p> <!-- Calls an instance method mixin, outputs: 'BARK BARK!' --> <button class="btn" ng-click="bark()">Bark Dog</button> <!-- Scope method mixin, outputs: 'run speed: 35mph' --> <button class="btn" ng-click="run()">Run Dog</button> </section> 

这个例子中的控制器都在全局空间中,并且被包括在标记中,如下所示。

 <script type="text/javascript" src="lib/jquery.js"></script> <script type="text/javascript" src="lib/angular.js"></script> <script type="text/javascript" src="app/controllers/animal-controller.js"></script> <script type="text/javascript" src="app/controllers/dog-controller.js"></script> <script type="text/javascript" src="app/controllers/cat-controller.js"></script> <script type="text/javascript" src="app/app.js"></script> 

我没有testing过,但我不明白为什么以下不会工作:

 var myApp = angular.module('myApp', []) .controller('AnimalController', ['$scope', 'vocalization', 'color', 'runSpeed', function ($scope, vocalization, color, runSpeed) { /* controller code here */}]); .controller('DogController', ['$scope', '$controller', function($scope, $controller) { var _this = this; // Mixin Animal functionality into Dog. angular.extend(this, $controller('AnimalController', { $scope: scope, vocalization: 'BARK BARK!', color: 'solid black', runSpeed:'35mph' })); $scope.bark = function () { _this.vocalize(); // inherited from mixin. } }]); 

请参阅:$控制器服务的文档

你想要的是可怕的。

你不希望你的控制者知道彼此的任何事情,更不用说,一个人可以访问另一个的function。 你可以使用一个服务来实现这一点。 至于使用指令,不知道你到底想要发生什么。

至于你的第二件事,你可以轻松做到这一点

 .service('MyTestService', function(){ return { testScope: function(){ console.log('It works'); } }; }) .controller('MyController', ['$scope', 'MyTestService', function($scope, MyTestService){ $scope.testScope = MyTestService.testScope; }]) 

并在你看来:

 <p ng-click="testScope()">ppp</p> 

我结束了:

 //service .service('PostUploader',function($upload){ var that = this; var fileReaderSupported = window.FileReader !== null; this.notify = null; this.success = null; this.showAlert = false; this.avatar = ''; this.onFileSelect = function($files) { var $file = $files[0]; var filename = $file.name; this.avatar = filename; var isImage = /\.(jpeg|jpg|gif|png)$/i.test(filename); if(!isImage){ this.showAlert = true; return; } this.showAlert = false; if (fileReaderSupported && $file.type.indexOf('image') > -1) { var fileReader = new FileReader(); fileReader.readAsDataURL($file); fileReader.onload = that.notify; } $upload.upload({ url :'/api/post/upload', method: 'POST', headers: {'x-ng-file-upload': 'nodeblog'}, data :null, file: $file, fileFormDataName: 'avatar' }) .success(that.success) .progress(function(evt) { }) .error(function(data, status, headers, config) { throw new Error('Upload error status: '+status); }) }; this.closeAlert = function() { this.showAlert = false; }; }) //controller /* Uploader post */ $scope.dataUrl = null; $scope.avatar = PostUploader.avatar; $scope.showAlert = PostUploader.showAlert; $scope.onFileSelect = PostUploader.onFileSelect; $scope.closeAlert = PostUploader.closeAlert; PostUploader.notify = function(e){ $timeout(function() { $scope.dataUrl = e.target.result; }); }; PostUploader.success = function(data, status, headers, config) { $timeout(function() { $scope.post.avatar = data.url; }); } $scope.$watch('avatar',function(newVal, oldVal){ if(newVal) { $scope.avatar = newVal; } }); $scope.$watch('showAlert',function(newVal, oldVal){ $scope.showAlert = newVal; $scope.dataUrl = null; }); 

我这样做是因为我必须在创build后和编辑后做同样的事情,但总而言之,我有相同的重复代码! 🙂

唯一的好处是代码的逻辑更less。

明显但辉煌的解决scheme(可能)

 (function(window, angular, undefined) { 'use strict'; angular.module('ctrl.parent', []) .run(function ($rootScope) { $rootScope.test = 'My test' $rootScope.myTest = function(){ alert('It works'); } }); })(window, angular); angular.module('app',['ctrl.parent']) .controller('ChildCtrl', function($scope){ }); 

这很容易,干净,没有任何缺点(这不是全球性的)

UPDATE

 'use strict'; (function(window, angular, undefined) { 'use strict'; angular.module('ctrl.parent', []) .controller('ParentController',function (scope) { scope.vocalization = ''; scope.vocalize = function () { console.log(scope.vocalization); }; }); })(window, angular); angular.module('app',['ctrl.parent']) .controller('ChildCtrl', function($scope,$controller){ angular.extend($scope, new $controller('ParentController', {scope:$scope})); $scope.vocalization = 'CIP CIP'; }); 

只是一个小整洁,它的作品CIP CIP 🙂