我正在使用 https://github.com/angular/angular-seed 的克隆版制作一个简单的 Angular.js 应用程序。我正在尝试向 Controller 添加一些属性,以便将它们绑定(bind)到我的 HTML 中,但不断收到我似乎无法弄清楚的错误消息。
我的 controllers.js 文件目前看起来像这样:
'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('MyCtrl1', [function($scope) {
$scope.names = 'bob'
}])
.controller('MyCtrl2', [function() {
}]);
如果有帮助,这里还有 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'});
}]);
我使用了应用程序“myApp”的默认名称,并且还在我的 HTML 中调用了 ng-view。使用 MyCtrl1 时,我不断收到此错误:
TypeError: Cannot set property 'names' of undefined
这里有语法错误吗?我试图只修改 controllers.js 以避免出现问题,所以其他地方不应该有问题......
最佳答案
Controller 有一些重载,您可以将代码简化为:
angular.module('myApp.controllers', []).
controller('MyCtrl1', function($scope) {
$scope.names = 'bob'
})
.controller('MyCtrl2', function() {
});
或者让 Angular 知道 $scope 是这样的:
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope', function($scope) {
$scope.names = 'bob'
}])
.controller('MyCtrl2', [function() {
}]);
引用:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller
关于html - Angular.js Controller 无法设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16308676/