Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs $scope undefined when controllers are inside a module

Tags:

angularjs

I'm trying to use the angular-seed template with the default settings. In controllers.js I use

angular.module('myApp.controllers', []).   controller('MyCtrl1', [function($scope) {       $scope.test = 'scope found!';   }])   .controller('MyCtrl2', [function() {    }]); 

There the $scope is always undefined. When I take the controller out of the module and register it globally it works fine. As here:

function MyCtrl1($scope) {     $scope.test = "scope found!"; } MyCtrl1.$inject = ['$scope']; 

Could someone explain to me why this is?

like image 371
Ashraf Fayad Avatar asked Apr 29 '13 17:04

Ashraf Fayad


2 Answers

You cannot mix things like that. You need to decide on one of the two possibilities:

app = angular.module('test', []);  // possibility 1 - this is not safe for minification because changing the name // of $scope will break Angular's dependency injection app.controller('MyController1', function($scope) {     // ... });  // possibility 2 - safe for minification, uses 'sc' as an alias for $scope app.controller('MyController1', ['$scope', function(sc) {     // ... }]); 

I would not advise using the other syntax which declares Controller directly. Sooner or later with the growth of you app it will become hard to maintain and keep track. But if you must, there are 3 possibilities:

function myController1 = function($scope) {     // not safe for minification }  function myController2 = ['$scope', function(sc) {     // safe for minification, you could even rename scope }]  var myController3 = function(sc) {     // safe for minification, but might be hard     // to read if controller code gets longer } myController3.$inject = ['$scope']; 
like image 110
TheHippo Avatar answered Oct 19 '22 04:10

TheHippo


This is the proper way:

angular.module('myApp.controllers', []);  angular.module('myApp.controllers').controller('MyCtrl1', ['$scope', function($scope) {  }]); 
like image 39
holographic-principle Avatar answered Oct 19 '22 03:10

holographic-principle