简体   繁体   中英

AngularJS service function execution order

I'm new to AngularJS. I created a service to retrieve a file using $http.get, but I can't figure out how to control when the service function is executed.

My controller's function is injected with the service.

When the page first loads, the service function is invoked first. Instead, I want the service function to be invoked after clicking a button.

Or maybe I shouldn't use a service function?

 var app = angular.module("app", []); app.controller("myCtrl", function($scope, $http, myService) { $scope.searchValues = function () { $scope.value = "search.json"; myService.setValue($scope.value); console.log(" in searchValues " + $scope.value); }; }); app.service("myService", function($http, $q) { var deferred = $q.defer(); var value ; this.setValue = function(valueSelected) { console.log("in service: " + valueSelected); value = valueSelected; }; $http.get('http://juubaker.github.io/' + value).then(function(data) { console.log("in service 2: " + value); deferred.resolve(data); }); this.getValue = function() { return deferred.promise; }; }); 

Thanks

Your service looks totally fine. Just don't call your myService.setValue method in your controller immediately like that. Instead, create a method that you run via ng-click

app.controller("myCtrl", function($scope, $http,  myService) {
  $scope.updateValue = function(){
    myService.setValue($scope.value);
  }
});

And your template:

<input type="text" ng-model="value" />
<a ng-click="updateValue()">Save Value</a>

The logic inside your controller method is run immediately upon initialization of that controller, which is why you're running into this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM