从控制器访问angularjs服务

Access angularjs services from a controller

本文关键字:服务 angularjs 访问 控制器      更新时间:2023-09-26

我已经添加了一些代码来阻止用户交互,而angular $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" fn只是调用$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