【问题标题】:AngularJs call controller function from factoryAngularJs 从工厂调用控制器功能
【发布时间】:2015-12-02 17:18:44
【问题描述】:

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

我的 Angular 代码:

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();
      }

    }
  ]);

我的 Angular 工厂代码:

'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发送到工厂?

【问题讨论】:

  • myApp.DbScripts是不同的模块,需要添加到控制器模块:angular.module('myApp.controllers', ['myApp.DbScripts'])
  • 我收到此错误:Uncaught Error: [$injector:modulerr]
  • 控制器不应该是调用工厂方法的那个吗?不是反过来吗?

标签: javascript jquery angularjs ajax


【解决方案1】:

您可以通过利用 $http 承诺来做到这一点,在您的工厂中,按如下方式返回承诺

'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

【讨论】:

  • 您好@Kashyap:感谢您的回复。实际上,现在我在工厂收到$http is not a function 错误。
  • 你能确定你已经注入了工厂函数吗?
  • angular.module('myApp.DbScripts', []) .factory('Task', [ function ($http) { return { query: function (data) { } } }]);
  • 试试angular.module('myApp.DbScripts', []) .factory('Task', ['$http', function ($http) { return { query: function (data) { } } }]);
  • 您的 Plunker 拥有.factory('Task', [ '$http',.then(function(result) {return result;}) 也是多余的,不需要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2014-05-02
相关资源
最近更新 更多