可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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(); });