![](/img/trans.png)
[英]Using ng-init to send data from a ng-repeat to another controller
[英]read ng-init data from controller
我是angularJS的新手,我想從contoller訪問ng-init數據,但始終返回undefined,這是我的代碼
的HTML
<div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
....
</div>
角度控制器
uniqcApp.controller('IFuseController', function (IFuseService, $scope) {
console.log("Cingda " + $scope.myText); //return undefined
});
任何想法?
發生這種情況是因為在加載時調用了控制器,而此時您沒有為變量myText設置值。
加載文本后,您需要觸發一個事件。
演示
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>
您可以強制將ng-init
結果綁定到$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>
為什么不在控制器端初始化數據? 如果您仍然想要這樣做,可以使用$ watch
$scope.$watch('myText',function(newVal){
alert(newVal);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.