简体   繁体   English

AngularJS服务功能执行顺序

[英]AngularJS service function execution order

I'm new to AngularJS. 我是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. 我创建了一个服务来使用$ http.get检索文件,但是我不知道如何控制何时执行服务功能。

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. 只是不要像这样立即在控制器中调用myService.setValue方法。 Instead, create a method that you run via ng-click 而是创建一个通过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. 控制器方法内部的逻辑在初始化该控制器后立即运行,这就是您遇到此问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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