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?
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.
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.
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.
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.
You can try to use a watch
$scope.$watch('data.id',function(newValue,oldValue) {
if(newValue) {
$http.get("/api/Something?id=" + $scope.data.id);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With