我是angularJS的新手,我想从控制器访问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
});
任何想法?
答案 0 :(得分:2)
这是因为您的控制器在加载时被调用,而那时您没有为变量 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>
答案 1 :(得分:0)
您可以强制将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);
});
&#13;
<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>
&#13;
答案 2 :(得分:0)
为什么不在控制器端初始化数据? 如果您仍想这样做,可以使用$ watch
$scope.$watch('myText',function(newVal){
alert(newVal);
})