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'?
ngInclude creates a new child scope which inherits scope values from the parent controller.
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.
The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.
The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
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); }); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With