Gusti Arya
Gusti Arya

Reputation: 1301

read ng-init data from controller

I am new to angularJS, I want to access ng-init data from contoller but always return undefined, here my code

HTML

<div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
....
</div>

Angular controller

uniqcApp.controller('IFuseController', function (IFuseService, $scope) {
   console.log("Cingda " + $scope.myText); //return undefined 
});

any idea?

Upvotes: 0

Views: 941

Answers (3)

Dakota
Dakota

Reputation: 525

Why dont you init data on controller side ? If you still want to do that , you can use $watch

$scope.$watch('myText',function(newVal){
   alert(newVal);
})

Upvotes: 0

Slava Utesinov
Slava Utesinov

Reputation: 13488

You can force to bind ng-init result to $scope:

var uniqcApp = angular.module('uniqueApp', []);
uniqcApp.controller('IFuseController', function($scope) {
  var el = angular.element(document.querySelector('[ng-controller=IFuseController]'));
  var attr = el[0].getAttribute('ng-init');
  $scope.$eval(attr);
  console.log("Cingda " + $scope.myText);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<body ng-app="uniqueApp">
  <div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
  </div>
</body>

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222532

This happens because your controller gets called on load, and that time you don't have value set for the variable myText.

You need to trigger an event once the text is loaded.

DEMO

var uniqcApp = angular.module('uniqueApp',[]);
uniqcApp.controller('IFuseController', function ($scope){
   $scope.read = function(){
     console.log("Cingda " + $scope.myText); 
   };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="uniqueApp">
<div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
  <button ng-click="read()">Read initial value</button> 
</div>
</body>

Upvotes: 2

Related Questions