我试图使用ng-init设置$ scope属性的值,我无法在控制器的javascript中访问该值.我究竟做错了什么?这是一个小提琴: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>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
var testController = function ($scope) {
console.log($scope.testInput);
}
Run Code Online (Sandbox Code Playgroud)
在javascrippt中,$ scope.testInput未定义.不应该'有价值'?
Alw*_*ner 46
您正在尝试在Angular完成分配之前读取设定值.
演示:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,您应该$watch按照@Beterraba的建议使用以摆脱计时器:
var testController = function ($scope) {
console.log('test');
$scope.$watch("testInput", function(){
console.log($scope.testInput);
});
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*Rob 40
只需将ng-init设置为函数即可.你不应该使用手表.
<body ng-controller="MainCtrl" ng-init="init()">
<div ng-init="init('Blah')">{{ testInput }}</div>
</body>
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.testInput = null;
$scope.init = function(value) {
$scope.testInput= value;
}
}]);
Run Code Online (Sandbox Code Playgroud)
这是一个例子.
| 归档时间: |
|
| 查看次数: |
100053 次 |
| 最近记录: |