Data configuration with angularjs coordinates between controllers

I am wondering what might be a good way to share the directive between the controller. I have two directives for use in different controllers with a different configuration, the first thing I thought about using:

//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) { }) 

By doing this, I can use all the functions in the controller of my children, but I don’t really like it because of collision problems. Since you cannot use the service (you cannot use $ scope in the service), other alternatives could make another directive or put the code in the execution block, but this is exactly the same using the parent controller, so what are you thinking about?

UPDATE

What do you think of this approach?

 //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 this seems like the best option :)

 MyTest.call($scope); 
0
angularjs angularjs-scope angularjs-directive angular-ui angular-ui-bootstrap
Jan 29 '14 at 9:34
source share
4 answers

Consider the method described in this post: Extending AngularJS Controllers Using the Mixin Template

Instead of copying your methods from the service, create a base controller that contains these methods, and then call the extension on your derived controllers to mix them. Example from the message:

 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 ); }; } 

Now we can mix AnimalController into 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. } } 

And then use DogController in our template:

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

The controllers in this example are in global space and are included in the markup as follows.

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

I have not tested it, but I do not understand why the following will not work:

 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. } }]); 

see docs for the $ controller service

+6
Jan 30 '14 at 18:57
source share

What you want is terrible.

You would not want your controllers to know anything about each other, not to mention that you have access to another's function. You can simply use the Service to achieve this. Regarding the use of directives, I'm not sure what exactly you want.

As for your second thing, you can just as easily do it

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

and in your opinion:

 <p ng-click="testScope()">ppp</p> 
+3
Jan 29 '14 at 10:21
source share

I ended up with:

 //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; }); 

I did this because I have to do the same in creating a message and editing a message, but overall I have the same duplicate code! :)

The only thing in the code has less logic.

0
Jan 30 '14 at 15:44
source share

obvious but brilliant solution (maybe)

 (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){ }); 

It is easy and clean and does not see any flaw (it is not global)

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'; }); 

a little neat and works CIP CIP :)

0
Jan 31 '14 at 19:47
source share



All Articles