myfunction()函数从angularjs

时间:2015-08-21 04:59:21

标签: javascript jquery asp.net-mvc angularjs

我使用了Angularjs,我想把getcustomer功能从一个控制器调到另一个控制器我有很多人在做gooogling但是我不知道如何调用它 我已经写下了我用过的代码

      var app = angular.module('Napp', []);
            app.controller('GetAlphabetical', function ($scope, $http) {

      function getCutomers() {
                $scope.loading = true;
                $http.get('@Url.Content("~/Home/GetPesrons")').then(function (response) {
                    //var _data = angular.fromJson(response);
                    $scope.loading = false;
                    $scope.Customer = response.data; // please check the request response if list id in data object 
                }, function (error) {
                    throw error;
                })
            }
    });



and second controller :

app.controller('MainCtrl', function ($scope, $http) {
getCutomers()
});

3 个答案:

答案 0 :(得分:1)

Mate,您必须按照以下步骤解决问题。首先,你要创建一个工厂

   angular
    .module('Napp')
    .factory('CustomerFactory', ['$http', function ($http) {
      var _factory = {};

      _factory.getCustomers = function () {
        return $http.get('@Url.Content("~/Home/GetPesrons")');
      };

      return _factory;
    }]);

然后,您可以在多个控制器或服务之间共享数据和功能

GetAlphabetical Controller:

   angular
    .module('Napp')
    .controller('GetAlphabetical', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {

      loadCustomers();

      function loadCustomers() {
        CustomerFactory.getCustomers().then(function (successResponse) {
          $scope.Customer = successResponse.data; // please check the request response if list id in data object 
        }, function (errorResponse) {
          throw error;
        })
      }

    }]);

MainCtrl控制器:

  angular
    .module('Napp')
    .controller('MainCtrl', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {

      loadCustomers();

      function loadCustomers() {
        CustomerFactory.getCustomers().then(function (successResponse) {
          $scope.Customer = successResponse.data; // please check the request response if list id in data object 
        }, function (errorResponse) {
          throw error;
        })
      }

    }]);

答案 1 :(得分:0)

你想要做的是以两种方式在两个控制器之间进行通信。使用$broadcast&可以很容易地实现这一点。 $on

如果您的控制器之间存在父子关系,请使用以下内容。

collectionBehavior

如果你的控制器之间没有父子关系,那么注入$rootScope并使用它进行广播。

相关问题 - https://stackoverflow.com/a/14502755/1182982

答案 2 :(得分:0)

通过将其定义为service并将其作为依赖项注入,可以轻松完成此操作。

var app = angular.module('myApp', []);

myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});

app.controller('MainCtrl', function ($scope, $http, helloWorldFromService) {

app.controller('GetAlphabetical', function ($scope, $http, helloWorldFromService) {

<强> Angular Service