{{message.test...">

Angular cannot set undefined property

I cannot understand why the following does not work:

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"; } }); 

When I run the code, I can report an error:

TypeError: it is not possible to set the 'test' property from undefined on the new ( http: // localhost: 9000 / scripts / controllers / main.js: 13: 25 ) when called ( http: // localhost: 9000 / bower_components / angular / angular. js: 4473: 17 ) in Object.instantiate ( http: // localhost: 9000 / bower_components / angular / angular.js: 4481: 27 ) on http: // localhost: 9000 / bower_components / angular / angular.js: 9108: 28 in $ 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 ) at compositeLinkFn ( http: // localhost: 9000 / bower_components / angular / angular.js: 7637: 13 ) in publicLinkFn ( http: // localhost: 9000 / bower_components / angular / angular.js: 7512: 30 ) with a name. $ get.boundTranscludeFn ( http: // localhost: 9000 / bower_components / angular / angular.js: 7656: 16 )

It is clear that I am missing something beyond the obvious.

+6
source share
4 answers

You define a property of an undefined object, you must initialize your object before setting the properties.

 $scope.message = {}; $scope.message.test = 'bla'; 
+25
source

You must initialize your $scope.message object, but do it safely (just in case, it is defined somewhere else, perhaps in some circles):

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

your test does not exist inside the message, you need to do $scope.message = {}; before, $scope.message.test = "blablabla";

+3
source

message in your code is not an object, you should do this:

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

All Articles