簡體   English   中英

從控制器訪問angularjs服務

[英]Access angularjs services from a controller

我添加了一些代碼來阻止有角度的$ http請求正在進行時的用戶交互:

controller.js:

var app = angular.module("my_app", ["my_app"]);
app.controller("MyController", ['$scope', '$http', function($scope, $http) {
  $scope.blocking = false;
  $scope.do_something = function() {
    $scope.blocking = true;
    $http({
      method: "POST",
      url: "some.url.com",
      data: my_data
    }).success(function(data) {
      // do something nice
    }).error(function(data) {
      // do some error handling
    }).finally(function() {
      $scope.blocking = false;
    });
  };
}]);

template.html:

<div ng-controller="MyController">
  <fieldset ng-disabled="blocking">
    <form>
      ...a bunch of form elements...
      ...including a "submit" button...
      ...some of which call "do_something" above...
    </form>
  </fieldset>
</div>

當我運行“ do_something” fn時,這會正確地將“ blocking”設置為true,這樣可以防止字段集內的所有用戶交互。 萬歲。

但是 ,我的代碼需要做很多這類事情。 因此,我嘗試將功能遷移到服務:

service.js:

app.factory('$my_service', ['$http', function($http) {
  _blocking = false;
  return {
    getBlocking: function() {
      return _blocking;
    },
    setBlocking: function(blocking) {
      _blocking = blocking;
    }
  }
}]);

然后,我上面的“ do_something”函數會根據需要簡單地調用$ my_service.setBlocking。 但是,我不知道要為ng-disabled的參數加些什么。

有什么建議么?


按照@ user449689的要求,這是新的控制器代碼:

app.controller("MyController", ['$scope', '$http', '$my_service', function($scope, $http, $my_service) {
  $scope.do_something = function() {
    $my_service.setBlocking(true);
    $http({
      method: "POST",
      url: "some.url.com",
      data: my_data
    }).success(function(data) {
      // do something nice
    }).error(function(data) {
      // do some error handling
    }).finally(function() {
      $my_service.setBlocking(false);
    });
  };
}]);

但是我不知道要在fieldset元素的“ ng-disabled”屬性中添加什么。

只需在控制器上更新$scope.blocking以引用服務方法$my_service.getBlocking並將HTML更新為

<fieldset ng-disabled="blocking()">

在控制器上

$scope.blocking = $my_service.getBlocking

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM