AngularJs从工厂调用控制器功能

AngularJs call controller function from factory

本文关键字:控制器 功能 调用 工厂 AngularJs      更新时间:2023-09-26

我正在尝试一个sample with angularJs,其中我正在尝试call a factory method,在工厂方法中,我正在执行ajax callback以从数据库获取结果,在ajax回调的success event中,我需要调用function in the controller来绑定result to the UI

我的角度代码:

angular.module('myApp.controllers', [])
  .controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
    function($scope, $rootScope, $routeParams, Task) {
      debugger;
      //factory call
      Task.query({
        MobileNumber: $routeParams.MobileNumber,
        ClientCode: $routeParams.ClientCode
      });
      $rootScope.UserMobileNumber = $routeParams.MobileNumber;
      $scope.BindTasksList = function(resultData) {
        debugger;
        $scope.Tasks = resultData;
        $scope.$apply();
      }
    }
  ]);

我的角度工厂代码:

'use strict';
(function() {
  function GetTasks(MobileNumber, ClientCode) {
    debugger;
    $.ajax({
      url: '/api/TasksAPI/GetTasksList',
      type: 'GET',
      datatype: 'json',
      data: {
        'MobileNumber': MobileNumber,
        'ClientCode': ClientCode
      },
      success: function(response) {
        debugger;
        $scope.BindTasksList(response);
      },
      error: function(xhr) {}
    });
  };
  angular.module('myApp.DbScripts', [])
    .factory('Task', [
      function() {
        return {
          query: function(data) {
            debugger;
            GetTasks(data.MobileNumber, data.ClientCode);
          }
        }
      }
    ]);
}());

我的app.js代码:

'use strict';
angular.module('myApp', [
  'ngTouch',
  'ngRoute',
  'ngAnimate',
  'myApp.controllers',
  'myApp.DbScripts'
]).
config(['$routeProvider',
  function($routeProvider) {
    debugger;
    $routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
      templateUrl: 'partials/tasks-list.html',
      controller: 'TasksListCtrl'
    });
    $routeProvider.when('/tasks/:taskId', {
      templateUrl: 'partials/task-details.html',
      controller: 'TaskDetailCtrl'
    });
    $routeProvider.when('/tasks/:taskId/status', {
      templateUrl: 'partials/task-completion-details.html',
      controller: 'TaskCompletionDetailCtrl'
    });
    $routeProvider.when('/tasks/:taskId/route', {
      templateUrl: 'partials/route-details.html',
      controller: 'RouteDetailCtrl'
    });
    $routeProvider.otherwise({
      redirectTo: '/tasks'
    });
  }
]);

但是,我无法调用控制器中的函数。我在angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response)上也试过。但即便如此也无济于事。

有人能指出我犯的错误吗
如何将控制器的$scope发送到工厂?

您可以通过利用$http promise来实现这一点,在您的工厂中,按如下返回promise

'use strict';
(function() {
  function GetTasks(MobileNumber, ClientCode) {
  };
  angular.module('myApp.DbScripts', [])
    .factory('Task', [
      function($http) {
        return {
          query: function(data) {
           return $http({
                   url: '/api/TasksAPI/GetTasksList',
                   method: 'GET',
                   params: {
                            'MobileNumber': data.MobileNumber,
                            'ClientCode': data.ClientCode
                           }
                }).then(function(result) {
                   return result;
                });
          }
        }
      }
    ]);
}());

然后在您的控制器中,您可以访问返回的$http响应对象:

      //factory call
      Task.query({
        MobileNumber: $routeParams.MobileNumber,
        ClientCode: $routeParams.ClientCode
      }).then(function(resp) {
           // access $http resp here and attach to $scope.Tasks
      });

如果可以的话,我建议您也使用$q$http,这样您就不需要解析http响应并返回一个漂亮的小响应数据对象

plnk