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 fidd
HTML:
<body ng-app="App">
<div ng-controller="testController" >
<input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
</div>
{{ testInput }}
</body>
JS:
angular.module('App', []);
testController = function ($scope) {
console.log('test');
$scope.$watch('testInput', testShow, true);
function testShow() {
console.log($scope.testInput);
}
}
Fiddle
Try this Code
var app = angular.module('myapp', []);
app.controller('testController', function ($scope, $http) {
$scope.init = function(){
alert($scope.testInput);
};});
<body ng-app="myapp">
<div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >
</div>
</body>
Like CodeHater said you are accessing the variable before it is set.
To fix this move the ng-init directive to the first div.
<body ng-app>
<div ng-controller="testController" ng-init="testInput='value'">
<input type="hidden" id="testInput" ng-model="testInput" />
{{ testInput }}
</div>
</body>
That should work!
I had some trouble with $scope.$watch
but after a lot of testing I found out that my data-ng-model="User.UserName"
was badly named and after I changed it to data-ng-model="UserName"
everything worked fine. I expect it to be the .
in the name causing the issue.
Just set ng-init as a function. You should not have to use watch.
<body ng-controller="MainCtrl" ng-init="init()">
<div ng-init="init('Blah')">{{ testInput }}</div>
</body>
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.testInput = null;
$scope.init = function(value) {
$scope.testInput= value;
}
}]);
Here's an example.
Plunker
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);
});
}