简体   繁体   中英

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?

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> 

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> 

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM