Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to wait for ng-init values to be set?

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?

like image 899
Eugene Osovetsky Avatar asked Sep 05 '13 05:09

Eugene Osovetsky


People also ask

How does ng-init work?

The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.

When Ng-INIT is called?

x, ngInit is called when template is re-rendered. In other words “ng-init” is called, when I take turns back to a page. In Angular2, there is no “ng-init” but we can create a ways like this using the directive and ngOnInit class. Angular 2 provides life cycle hook ngOnInit by default.

Why do we use NG repeat?

Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is Ng on init in angular?

ngOnInit()link A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.


1 Answers

You can try to use a watch

$scope.$watch('data.id',function(newValue,oldValue) {
  if(newValue) {
    $http.get("/api/Something?id=" + $scope.data.id);
  }
});
like image 114
Chandermani Avatar answered Sep 17 '22 12:09

Chandermani