2015-09-11 41 views
6

nie mogę zupełnie zrozumieć, dlaczego następujące nie działa:kątowa nie można ustawić właściwość nieokreślonej

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

    } 
}); 

kiedy uruchom kod Mogę wskazać błąd:

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)

Najwyraźniej brakuje mi czegoś bardzo oczywistego ..

Odpowiedz

25

Definiujesz właściwość obiektu niezdefiniowanego , musisz zainicjować obiekt przed ustawieniem właściwości.

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

Twój testu nie istnieje wewnątrz wiadomości, trzeba zrobić $scope.message = {}; wcześniej $scope.message.test = "blablabla";

3

message w kodzie nie jest obiektem, trzeba zrobić to:

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

Ty powinien zainicjować twój obiekt $scope.message, ale zrób to bezpiecznie (na wypadek gdyby został zdefiniowany gdzie indziej, może w niektórych okolicznościach):

$scope.message = $scope.message || {}; 
$scope.message.test = "blablabla"; 
Powiązane problemy