9

I have an "ng-init" directive in my HTML that initializes the value of "data.id" in my Angular.js data model. Let's say for now that I can't change how this works.

Now, I want to make an HTTP request as soon as my page loads, where the URL will depend on this data.id value. So far, the following seems to work:

app.controller('MainCtrl', function ($scope, $http, $timeout) {
  "use strict";

  $scope.data = {};

  $timeout(function () {
    $http.get("/api/Something?id=" + $scope.data.id);
  }, 0);
});

However, using a timer with a timeout of zero seems clunky. (And if I omit the $timeout code and simply call $http.get directly, then $scope.data.id is, of course, undefined).

Is there a better way to wait until ng-init has executed before issuing the $http request? And is the timeout-based code above guaranteed to work in all cases / on all browsers, etc?

4

1 回答 1

5

您可以尝试使用手表

$scope.$watch('data.id',function(newValue,oldValue) {
  if(newValue) {
    $http.get("/api/Something?id=" + $scope.data.id);
  }
});
于 2013-09-05T07:36:31.070 回答