0

我有一个控制器/服务等定义如下:

function IndexController($scope, shoppingItems) {
     $scope.items = shoppingItems;
 }

然后我想知道我所有的 JS 是否应该像这样从全局命名空间中保护起来:

 (function() {

     function IndexController($scope, shoppingItems) {
         $scope.items = shoppingItems;
     }
 });

我的应用程序不再工作,你能解释一下我是否需要这样做,如果需要,如何让它工作。

谢谢

4

2 回答 2

0

您最后缺少一对括号,使您的函数成为立即评估的函数:

(function() {
     function IndexController($scope, shoppingItems) {
         $scope.items = shoppingItems;
     }
 })();
于 2013-01-30T10:22:55.370 回答
0

我建议您使用新样式的注册控制器(至少从 开始1.0.3,可能也是1.0.1如此)

(function() {
  //this will simulate creating the app with all needed dependencies
  var app = angular.module('app', ['my.dependecy1', 'my.dependecy1']);
  //...init code maybe
});

(function() {
  //this will only retrieve it or create if it it doesn't exist
  //I suggest you create it in another place passing all needed dependencies
  var app = angular.module('app');

  //I also recommend listing injectable variables manually,
  //this way if you ever need minification you're safe
  app.controller('IndexController', ['$scope', 'shoppingItems', 
     function IndexController($scope, shoppingItems) {
         $scope.items = shoppingItems;
     }
  ]);

}());
于 2013-01-30T14:10:17.167 回答