我有一个控制器/服务等定义如下:
function IndexController($scope, shoppingItems) {
$scope.items = shoppingItems;
}
然后我想知道我的所有JS是否应该像全局名称空间一样受到保护:
(function() {
function IndexController($scope, shoppingItems) {
$scope.items = shoppingItems;
}
});
我的应用程序不再有效,您能解释一下我是否需要这样做,如果是这样,该如何让它正常运行。
由于
答案 0 :(得分:0)
你最后错过了一对括号,使你的函数成为一个立即评估的函数:
(function() {
function IndexController($scope, shoppingItems) {
$scope.items = shoppingItems;
}
})();
答案 1 :(得分: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;
}
]);
}());