18

I can't quite figure out why the following isn't working:

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 an error that states:

TypeError: Cannot set property 'test' of undefined at new (http://localhost:9000/scripts/controllers/main.js:13:25) at invoke (http://localhost:9000/bower_components/angular/angular.js:4473:17) at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4481:27) at http://localhost:9000/bower_components/angular/angular.js:9108: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) at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7637:13) at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:7512:30) at name.$get.boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:7656:16)

Clearly I'm missing something super obvious..

0

4 Answers 4

46

You're defining a property to an undefined object, you have to initialized your object before setting properties.

$scope.message = {};
$scope.message.test = 'bla';
Sign up to request clarification or add additional context in comments.

Comments

6

You should initialize your $scope.message object, but do it safely (just in case it's defined somewhere else, maybe in some circumstanes):

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

1 Comment

even after 7 yrs you solution works for me. your last seen was 2 yrs ago. Where ever you're, i wish you will find strength with each new day .
4

message in your code is not an object, you must make it:

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.