Angular.js Controller无法设置属性

时间:2021-12-03 21:05:23

I'm using a clone of https://github.com/angular/angular-seed to make a simple Angular.js app. I'm trying to put in some properties to the controllers in order to bind them in my HTML but keep getting errors messages that I can't seem to figure out.

我正在使用https://github.com/angular/angular-seed的克隆来制作一个简单的Angular.js应用程序。我正在尝试向控制器添加一些属性,以便在我的HTML中绑定它们,但不断收到我似乎无法弄清楚的错误消息。

My controllers.js file looks like this currently:

我的controllers.js文件目前看起来像这样:

'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('MyCtrl1', [function($scope) {
    $scope.names = 'bob'
  }])
  .controller('MyCtrl2', [function() {

  }]); 

Here is the app.js too if it helps:

如果它有帮助,这里也是app.js:

'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',     'myApp.controllers']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller:  'MyCtrl1'});
    $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);

I've used the default name for the app "myApp" and have also called the ng-view within my HTML. When MyCtrl1 is in use I continually get this error:

我已经使用了应用程序“myApp”的默认名称,并且还在我的HTML中调用了ng-view。当MyCtrl1正在使用时,我不断收到此错误:

TypeError: Cannot set property 'names' of undefined

Is there something syntactically wrong here? I've tried to only modify controllers.js to avoid having issues so there shouldn't be problems elsewhere...

这里有什么语法错误吗?我试图只修改controllers.js以避免出现问题所以其他地方不应该出现问题......

1 个解决方案

#1


14  

Controllers has a few overloads, you can either simplify your code to this:

控制器有一些重载,你可以简化你的代码:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', function($scope) {
    $scope.names = 'bob'
  })
  .controller('MyCtrl2', function() {

  }); 

Or let Angular know what $scope is like this:

或者让Angular知道$ scope是这样的:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope', function($scope) {
    $scope.names = 'bob'
  }])
  .controller('MyCtrl2', [function() {

  }]); 

Reference: http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

#1


14  

Controllers has a few overloads, you can either simplify your code to this:

控制器有一些重载,你可以简化你的代码:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', function($scope) {
    $scope.names = 'bob'
  })
  .controller('MyCtrl2', function() {

  }); 

Or let Angular know what $scope is like this:

或者让Angular知道$ scope是这样的:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope', function($scope) {
    $scope.names = 'bob'
  }])
  .controller('MyCtrl2', [function() {

  }]); 

Reference: http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller