TimH TimH - 1 month ago 12
AngularJS Question

How to set scope property with ng-init?

I am trying to set the value of a $scope property using ng-init, and I am unable to access that value in the controller's javascript. What am I doing wrong? Here is a fiddle: http://jsfiddle.net/uce3H/

markup:

<body ng-app>
<div ng-controller="testController" >
<input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput='value'" />
</div>
{{ testInput }}
</body>


javascript:

var testController = function ($scope) {
console.log($scope.testInput);
}


In the javascrippt, $scope.testInput is undefined. Shouldn't be 'value'?

Answer

You are trying to read the set value before Angular is done assigning.

Demo:

var testController = function ($scope, $timeout) {
    console.log('test');
    $timeout(function(){
        console.log($scope.testInput);
    },1000);
}

Ideally you should use $watch as suggested by @Beterraba to get rid of the timer:

var testController = function ($scope) {
    console.log('test');
    $scope.$watch("testInput", function(){
        console.log($scope.testInput);
    });
}
Comments