如何使用ng-init设置作用域属性? [英] How to set scope property with ng-init?
本文介绍了如何使用ng-init设置作用域属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ng-init设置$ scope属性的值,但无法在控制器的javascript中访问该值.我究竟做错了什么?这是一个小提琴: http://jsfiddle.net/uce3H/
I am trying to set the value of a $scope property using ng-init, and I am unable to access that value in the controller's javascript. What am I doing wrong? Here is a fiddle: http://jsfiddle.net/uce3H/
标记:
<body ng-app>
<div ng-controller="testController" >
<input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput='value'" />
</div>
{{ testInput }}
</body>
javascript:
javascript:
var testController = function ($scope) {
console.log($scope.testInput);
}
在javascrippt中,$ scope.testInput是未定义的.不应该是价值"吗?
In the javascrippt, $scope.testInput is undefined. Shouldn't be 'value'?
推荐答案
您正在尝试在Angular完成分配之前读取设置值.
You are trying to read the set value before Angular is done assigning.
演示:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
理想情况下,应按照@Beterraba的建议使用$watch
来摆脱计时器:
Ideally you should use $watch
as suggested by @Beterraba to get rid of the timer:
var testController = function ($scope) {
console.log('test');
$scope.$watch("testInput", function(){
console.log($scope.testInput);
});
}
这篇关于如何使用ng-init设置作用域属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文