当控制器模块内不确定AngularJs $范围 [英] AngularJs $scope undefined when controllers are inside a module

查看:85
本文介绍了当控制器模块内不确定AngularJs $范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用角种子模板使用默认设置。在 controllers.js 我用

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?

推荐答案

您不能混用之类的东西。您需要在两个可能性之一决定:

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

我不建议使用其它语法直接宣告控制器。早晚用你的应用程式的增长将变得难以维护和跟踪。但是,如果你一定要,有3种可能性:

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

这篇关于当控制器模块内不确定AngularJs $范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆