Angular不能设置undefined属性
Angular cannot set property of undefined
我不太明白为什么下面的代码不工作:
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";
- jQuery可以't获取data-*属性值,返回undefined
- Slick jQuery: TypeError 无法读取 undefined 的属性 'unslick'
- 将服务中的函数绑定到$scope(错误:无法设置undefined的属性'onChange')
- 为什么调试器会给你“;undefined不是函数“;而不是只告诉您不是函数的属性/变量的名称
- 访问javascript对象的属性返回undefined,原因是什么
- app.render[TypeError:无法设置undefined的属性'content']在Node
- Google Maps 和 Angular js:TypeError:无法读取 undefined 的属性“触发器”
- jQuery Tablesorter 错误“未捕获的类型错误:无法设置 undefined 的属性'count&
- HTML 自定义属性在 Jquery 中始终返回 undefined
- AngularUI-Bootstrap的Typeahead无法读取“undefined”的“length”属性
- JS:如何返回“undefined”而不是抛出错误“无法读取未定义的属性x”
- .done() 无法读取 undefined 的属性
- findRecord给出错误"无法读取属性'undefined"
- Unslider -不能读取属性'undefined'的定义
- 在updateAttributes id属性undefined到undefined上环回失败
- Angular 2 -示例代码-定义模型属性Undefined
- jQuery多维数组(动态键)-不能设置属性undefined
- CSS with JavaScript -无法读取属性'undefined'错误
- 无法读取属性'undefined'的定义
- 无法读取属性'undefined"当使用AngularJS在谷歌地图上绘制标记时