Run once when AngularJS controller loads

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I have some stuff that needs to be done only once when the controller is loaded. What's the best way to this? I've read some about the "run block" but I don't really understand how it works.

Some pseudo code:

when /app resolove some stuff load a view controllerA  ControllerA:  Some-magic-piece-of-code-only-run-once{  }

Can anyone point me in the right direction?

回答1:

Just do it normally, controllers are just functions injected with $scope, services. When the controller is loaded, this function is called only once. You can do anything inside it.

app.controller("yourController",function($scope, myService){    //Write your logic here.      //Initialize your scope as normal });


回答2:

I always use ngInit.

HTML:

<div ng-controller="AppController" ng-init="init()"/>

JS:

$scope.init = function () {   // do something };

The code specified in your controller function is run only once, too:

var AppController = function($scope) {   // do something very early    $scope.init = function () {     // do something on loaded   };  };


回答3:

Sorry for late response. If you want some functionality to run only once (on application load time) and it depends on some functionality in controller then you'll need to put that functionality in a service/factory and you'll inject that service in the run block (associated to that service) which will be executed just after the service is loaded. If you won't inject service in run block then run block will be executed first independent of your service. So this is what will serve your purpose:

angular.module('myangularapp') .factory('myLogger', ['$http', 'apiUrl', function ($http, apiUrl) {     'use strict';     function PostService() {         $http({             url: apiUrl + 'TestEndPoint',             dataType: 'json',             method: 'post',             data: //some object         }).then(function success(response) {         }, function errorCallback(errorThrown) {         });     }      return {         PostService: PostService     } }]) .run(function (myLogger, $rootScope) { myLogger.PostService(); });


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!