Balachandiran
Balachandiran

Reputation: 661

How to get the init value in HTML to contoller in Angularjs on page load

<ul>                                                                
<li ng-init="formData.mdpSunday='5'">
<input ng-model="formData.mdpSunday" name="mdpSunday" type="radio" value="5">
</li>
</ul>


app.controller('doublePointCtrl', function ($rootScope, $scope, $http, $filter, Flash) {
var data =$scope.formData.mdpSunday;
});

i could not get the init values in controller while page loading

Upvotes: 1

Views: 2646

Answers (2)

Paul Boutes
Paul Boutes

Reputation: 3315

You want to read the ngInit value before Angular set the value.

First option :

So you can listen your ngInit value, and read your data when she will be set. You can use the $watch method :

Controller

(function(){

function Controller($scope) {

  //Watch you ngInit value
  $scope.$watch('data', function(){
    //When your value is set, you can retrieve it
    console.log($scope.data);
  });


}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

HTML

  <body ng-app='app' ng-controller="ctrl" ng-init="data='5'">

    <input type="text" ng-model="data">

  </body>

But, you should not have to use $watch. You can get a more efficient and proper way to achieve this.

Second Option :

You can set ngInit as a function.

Controller

(function(){

function Controller($scope) {

  $scope.init = function(n){
    $scope.data = n;
  }


}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

HTML

  <body ng-app='app' ng-controller="ctrl" ng-init="init(5)">

    <input type="text" ng-model="data">

  </body>

I think that the the second option is cleaner.

Upvotes: 5

michelem
michelem

Reputation: 14590

You need to wait the variable is init, $watch it

JSFiddle

$scope.formData = {};

$scope.$watch('formData.mdpSunday', function (newVal, oldVal) {
    console.log(newVal);
});

Upvotes: 0

Related Questions