Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set scope property with ng-init?

Tags:

angularjs

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'?

like image 306
TimH Avatar asked Nov 14 '13 15:11

TimH


People also ask

Does Ng include create a new scope?

ngInclude creates a new child scope which inherits scope values from the parent controller.

What is ng-init used for?

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.

What is ngInit?

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.

What is the role of Ng app ng-init and NG model directives?

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.


2 Answers

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);     }); } 
like image 85
AlwaysALearner Avatar answered Sep 21 '22 19:09

AlwaysALearner


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

like image 42
Rob Avatar answered Sep 17 '22 19:09

Rob