Angular不能设置undefined的属性

11 javascript angularjs

我无法弄清楚为什么以下不起作用:

main.html中

<div class="MainCtrl">
  <h1>{{message.test}}</h1>
</div>
Run Code Online (Sandbox Code Playgroud)

main.js

angular.module('myApp')
  .controller('MainCtrl', function(someService, $location, $scope) {

    $scope.message.test = "blablabla";

  }
});
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我可以发出一个错误,指出:

TypeError:无法在调用时设置undefined属性'test'(http:// localhost:9000/scripts/controllers/main.js:13:25)(http:// localhost:9000/bower_components/angular/angular). js:4473:17)在http:// localhost:9000/bower_components/angular/angular.js:9108的 Object.instantiate(http:// localhost:9000/bower_components/angular/angular.js:4481:27): 28 at $ route.link(http:// localhost:9000/bower_components/angular-route/angular-route.js:977:26)at invokeLinkFn(http:// localhost:9000/bower_components/angular/angular.js: 8746:9)at nodeLinkFn(http:// localhost:9000/bower_components/angular/angular.js:8246:11)在publicLinkFn(http:// localhost:9000/bower_components/angular/angular.js:7637:13)的publicLinkFn(http:// localhost:9000/bower_components/angular/angular.js:7512​​:30)处. $ get.boundTranscludeFn(http:// localhost:9000/bower_components/angular/angular.js:7656:16)

显然,我错过了一些非常明显的东西......

Pau*_*tes 40

您正在为未定义的对象定义属性,您必须在设置属性之前初始化对象.

$scope.message = {};
$scope.message.test = 'bla';
Run Code Online (Sandbox Code Playgroud)


slo*_*mek 5

您应该初始化您的$scope.message对象,但是要安全地进行操作(以防万一在其他地方(可能在某些情况下)定义了它):

$scope.message = $scope.message || {}; 
$scope.message.test = "blablabla";
Run Code Online (Sandbox Code Playgroud)