Angular不能设置undefined属性

Angular cannot set property of undefined

本文关键字:属性 undefined 设置 不能 Angular      更新时间:2023-09-26

我不太明白为什么下面的代码不工作:

main.html

<div class="MainCtrl">
  <h1>{{message.test}}</h1>
</div>

main.js

angular.module('myApp')
  .controller('MainCtrl', function(someService, $location, $scope) {
    $scope.message.test = "blablabla";
  }
});

当我运行代码时,我可以看到如下错误:

TypeError: Cannot set property 'test' of undefinedAt new (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.js: 4481:27)在http://localhost: 9000/bower_components/角度/angular.js: 9108:28美元的路线。链接(http://localhost: 9000/bower_components/angular-route/angular-route.js: 977:26)在invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8746:9)at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8246:11)网址:compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7637:13)网址:publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:7512:30)在获得美元的名字。。boundTranscludeFn (http://localhost: 9000/bower_components/角度/angular.js: 7656:16)

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

当你为未定义的对象定义属性时,你必须在设置属性之前初始化你的对象。

$scope.message = {};
$scope.message.test = 'bla';

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

$scope.message = $scope.message || {}; 
$scope.message.test = "blablabla";

message在你的代码中不是一个对象,你必须使它:

$scope.message = { test: 'blablabla' };

您的测试不存在于消息中,您需要在$scope.message = {};之前,$scope.message.test = "blablabla";