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?

Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59
  • i would suggest your model or controller looking after the data and the view just reflecting the data, not setting it. that is a much more "angular" approach imho – Anton Sep 05 '13 at 05:58

1 Answers1

5

You can try to use a watch

$scope.$watch('data.id',function(newValue,oldValue) {
  if(newValue) {
    $http.get("/api/Something?id=" + $scope.data.id);
  }
});
Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • Thanks! This seems to work and I've accepted the answer. I'm curious though whether there's an answer to the 2nd part of my question (if I kept the $timeout code, is it guaranteed to work or does it just happen to work?) – Eugene Osovetsky Sep 05 '13 at 16:29
  • Have a look at this discussion on SO. http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful#comment14183689_779785. Hope it helps you :) It may not work if there is a substantial delay. – Chandermani Sep 06 '13 at 03:44
  • but this thing will fire each time the data.id changes, not only on fist init, isn't it? – serge Jul 28 '17 at 15:15