2013-04-29 64 views
44

我正在嘗試使用帶默認設置的angular-seed模板。在controllers.js我用

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

    }]); 

那裏$scope總是不確定的。 當我將控制器從模塊中取出並全局註冊時,它可以正常工作。由於這裏:

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

有人能向我解釋這是爲什麼?

回答

65

你不能混合這樣的事情。您需要在兩個可能一個決定:

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

我不會建議使用其他的語法,直接宣告控制器。隨着應用程序的增長,遲早會變得難以維護和跟蹤。但是,如果你一定要,有3種可能性:

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']; 
+1

感謝解釋。我仍然想知道如何使用google在其模板中提供的默認語法來獲取對$ scope的引用: angular.module('myApp.controllers',[])。 控制器( 'MyCtrl1',[函數(){ }]) .controller( 'MyCtrl2',[函數(){ }]); – 2013-04-29 18:05:09

+0

@AshrafFayad獲得對'$ scope'的引用的唯一方法是用上述方法之一定義一個控制器。 – TheHippo 2013-04-29 18:29:56

+0

並非完全如此,實際上你忽視了我認爲是最喜歡的方式。 – finishingmove 2013-06-20 07:17:49

0

我也尋找那一個,似乎你需要的功能之前,鍵入'$scope',如下:

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

    }]); 

這有點讓某種意義上說,我覺得應該是,雖然更加清晰..

+0

'$ scope''需要放置在正確的位置。 – Zeeshan 2014-01-27 11:19:19

17

這是正確的方式:

angular.module('myApp.controllers', []); 

angular.module('myApp.controllers').controller('MyCtrl1', ['$scope', function($scope) { 

}]); 
-1

當您使用$ scope時,您可以簡單地刪除'['和']'。

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

 
    } 
 
    ]);

+0

使用範圍(或任何其他方法)時,您不能*僅刪除[]。你可以做到,如果你不關心縮小,這是完全不同的。 – 2017-02-03 11:20:49

相關問題