Eug*_*sky 9 angularjs angularjs-controller angularjs-timeout
我的HTML中有一个" ng-init "指令,它在我的Angular.js数据模型中初始化" data.id " 的值.我们现在说,我无法改变其运作方式.
现在,我希望在页面加载后立即发出HTTP请求,其中URL将取决于此data.id值.到目前为止,以下似乎有效:
app.controller('MainCtrl', function ($scope, $http, $timeout) {
"use strict";
$scope.data = {};
$timeout(function () {
$http.get("/api/Something?id=" + $scope.data.id);
}, 0);
});
Run Code Online (Sandbox Code Playgroud)
但是,使用超时为零的计时器似乎很笨拙.(如果我省略$ timeout代码并直接调用$ http.get,那么$ scope.data.id当然是未定义的).
在发出$ http请求之前,有没有更好的方法等待ng-init执行?以上基于超时的代码是否适用于所有情况/所有浏览器等?
你可以尝试使用手表
$scope.$watch('data.id',function(newValue,oldValue) {
if(newValue) {
$http.get("/api/Something?id=" + $scope.data.id);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5926 次 |
| 最近记录: |