加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

当控制器在模块内部时,AngularJs $scope未定义

发布时间:2020-12-17 08:57:12 所属栏目:安全 来源:网络整理
导读:我试图使用角种子模板与默认设置。在我使用的controllers.js angular.module('myApp.controllers',[]). controller('MyCtrl1',[function($scope) { $scope.test = 'scope found!'; }]) .controller('MyCtrl2',[function() { }]); $ scope总是未定义。 当我把
我试图使用角种子模板与默认设置。在我使用的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'];

有人可以向我解释为什么会这样吗?

你不能混合这样的东西。你需要决定两种可能性之一:
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) {
    // ...
}]);

我不建议使用其他语法直接声明Controller。迟早或随着你的应用程序的增长将变得难以维护和跟踪。但如果你必须,有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'];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读