如何使用 ng-init 设置范围属性? [英] How to set scope property with ng-init?
问题描述
我正在尝试使用 ng-init 设置 $scope 属性的值,但我无法在控制器的 javascript 中访问该值.我究竟做错了什么?这是一个小提琴:http://jsfiddle.net/uce3H/
标记:
<div ng-controller="testController" ><input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput='value'"/>
{{ 测试输入 }}
javascript:
var testController = function ($scope) {控制台日志($scope.testInput);}
在 javascript 中,$scope.testInput 是未定义的.不应该是'值'吗?
您正试图在 Angular 完成分配之前读取设置值.
演示:
var testController = function ($scope, $timeout) {console.log('test');$超时(功能(){控制台日志($scope.testInput);},1000);}
理想情况下,您应该按照@Beterraba 的建议使用 $watch
来摆脱计时器:
var testController = function ($scope) {console.log('test');$scope.$watch("testInput", function(){控制台日志($scope.testInput);});}
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/
markup:
<body ng-app>
<div ng-controller="testController" >
<input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput='value'" />
</div>
{{ testInput }}
</body>
javascript:
var testController = function ($scope) {
console.log($scope.testInput);
}
In the javascrippt, $scope.testInput is undefined. Shouldn't be 'value'?
You are trying to read the set value before Angular is done assigning.
Demo:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
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屋!