如何在Angular Js中定义范围根中的函数?

时间:2015-03-02 02:41:12

标签: angularjs

我写了一个简单的函数,它发出一个ajax请求来获取一些邮政编码信息。函数" GetAddressByZipCode()"在名为" ProposalController" 的控制器中定义,它可以正常工作。

现在,我需要将相同的功能放在另一个控制器中,在这种情况下" ContactController"。如何在范围根中定义此函数? 它需要能够在任何其他控制器中使用。

请参阅以下代码:

 myApp.controller('ProposalController', ['$scope',  '$http', function ($scope,  $http){
 function GetAddressByZipCode(zipcode) {

    $http.get('api/cep/consulta/' + zipcode)
         .success(function (data, status, headers, config) {
             if (data != null) {
                 $scope.address = data.address;
                 $scope.borough = data.borough.description;
                 $scope.city = data.city.description;
                 $scope.state = data.city.state.description;
             }
         })
         .error(function (data) {
             console.log("Error!");
         });
}}

 myApp.controller('ContactController', ['$scope',  '$http', function ($scope,  $http){
     /*I need to invoke the GetAddressByZipCode(zipcode) here*/
  }

3 个答案:

答案 0 :(得分:1)

您可以使用$rootScope附加功能并从整个应用中的任何位置访问该功能,但最好使用此类任务的服务

myApp.controller('ProposalController', ['$scope',  '$http', '$rootScope',function ($scope,  $http,$rootScope){
$rootScope.GetAddressByZipCode  = function GetAddressByZipCode(zipcode) {

$http.get('api/cep/consulta/' + zipcode)
     .success(function (data, status, headers, config) {
         if (data != null) {
             $scope.address = data.address;
             $scope.borough = data.borough.description;
             $scope.city = data.city.description;
             $scope.state = data.city.state.description;
         }
     })
     .error(function (data) {
         console.log("Error!");
     });
 }
}]);

myApp.controller('ContactController', ['$scope',  '$http','$rootScope' function ($scope,  $http,$rootScope){
 /*I need to invoke the GetAddressByZipCode(zipcode) here*/
 $rootScope.GetAddressByZipCode();
  }]);

答案 1 :(得分:0)

我的建议是,使用服务代替污染$ rootScope。您可以使用工厂来获取数据并在整个应用程序中重复使用相同的功能

(function () {
'use strict';
  angular
.module("myApp")
.factory('getZipFactory', [
  '$scope',
  '$log',
  '$http',
  getZipFunction
]);

function getZipFunction($scope, $log, $http) {
return{
  getAddressByZipCode : function (zipCode) {
    $http.get('api/cep/consulta/' + zipcode)
      .success(function (data) {
        if (data != null) {
          return data
        }
      })
      .error(function (data) {
        console.log("Error!" + data);
      });
  }

}

}

}();
在控制器中

可以使用

之类的东西
(function(){
    'use strict';
    angular
        .module("myApp")
        .controller('ProposalController',[
            '$scope',
            '$log',
            'getZipFactory',
             ProposalControllerFunction
            ]);

     function ProposalControllerFunction($scope, $log, getZipFactory){

       $scope.myData = function (someZip ) {
          var promise = getZipFactory.getAddressByZipCode(someZip);
           promise.then(function (success) {
             $scope.myZipCode = success;
            });
       }

     }

   }());

答案 2 :(得分:0)

您可以使用services文件夹和controllers文件夹来隔离职责。

每项服务必须是一个文件,例如categories.js

'use strict';

/**
 * @ngdoc service
 * @name spawesomeApp.Categories
 * @description
 * # Categories
 * Factory in the spawesomeApp.
 */
 angular.module('spawesomeApp')
 .factory('Categories', function ($http, appConfig) {

    var urlBase = appConfig.API_URL() + '/Category';
    var dataFactory = {};

    dataFactory.getCategories = function () {
      return $http.get(urlBase);
    };

    dataFactory.getCategory = function (id) {
      if(id == null)
        throw 'Id não informado';
      return $http.get(urlBase + '/' + id);
    };

    dataFactory.getCategoryBySlug = function(slug){
      if(slug == null)
        throw 'Slug não informado';
      return $http.get(urlBase + '/Slug/' + slug);
    };

    dataFactory.insertCategory = function (category) {
      if(category == null)
        throw 'category não informada';
      return $http.post(urlBase, category);
    };

    dataFactory.updateCategory = function (category) {
      if(category == null)
        throw 'category não informada';
      return $http.put(urlBase + '/' + category.Id, category)
    };

    dataFactory.deleteCategory = function (id) {
      if(id == null)
        throw 'Id não informado';
      return $http.delete(urlBase + '/' + id);
    };

    dataFactory.getSubCategories = function (id) {
      if(id == null)
        throw 'Id não informado';
      return $http.get(urlBase + '/' + id + '/SubCategories');
    };

    return dataFactory;

  });

正如您所看到的,我用来隔离API变量的“appConfig”服务。查看https://github.com/lazarofl/SPAwesome/tree/master/FrontEnd/app/scripts/services

处的整个“服务”文件夹

在控制器中,您可以引用要在控制器构造函数上注入服务名称的每个服务,如下面的代码。

'use strict';

/**
 * @ngdoc function
 * @name spawesomeApp.controller:CategoriesCtrl
 * @description
 * # CategoriesCtrl
 * Controller of the spawesomeApp
 */
 angular.module('spawesomeApp')
 .controller('CategoriesCtrl', function ($scope, $location, $log, $modal, Categories)
 {
    $scope.categories;
    $scope.alerts = [];
    $scope.loading = false;
    $scope.showadd = false;
    $scope.name = '';

    $scope.go = function ( path ) {
        $location.path( path );
    };

    $scope.addAlert = function(message, type) {
        $scope.alerts.push({type: type, msg: message});
    };

    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };

    $scope.init = function(){
        $scope.loading = true;
        Categories
        .getCategories()
        .success(function(data){
            $scope.categories = data;
            $scope.loading = false;
        }).
        error(function(error){
            $scope.addAlert('Não foi possível conectar na API, verifique a disponibilidade do serviço', 'danger');
            $scope.loading = false;
        });
    };

    $scope.editCategoryModal = function (index) {
        var modalInstance = $modal.open({
            templateUrl: 'editCategoryModalContent.html',
            controller: 'ModalEditCategoryCtrl',
            size: 'lg',
            resolve: {
                category: function () {
                    return $scope.categories[index];
                },
                name: function(){
                    return $scope.categories[index].Name;
                }
            }
        });

        modalInstance.result.then(function (category) {
            $scope.addAlert('Categoria altera: "' + category.Name + '"','success');
        }, function () {

        });
    };

    $scope.addCategory = function(){
        $scope.loading = true;

        var category = {
            Name: $scope.name
        };

        Categories
        .insertCategory(category)
        .success(function(data){
            $scope.init();

            $scope.addAlert($scope.name + ' adicionado com sucesso','success');
            $scope.name = '';
            $scope.showadd = false;
        }).
        error(function(error){
            if(!!error)
                $scope.addAlert(error.ExceptionMessage, 'danger');
            else
                $scope.addAlert('Não foi possível adicionar a categoria, verifique a disponibilidade do serviço', 'danger');
            $scope.loading = false;
        });
    };

    $scope.remove = function(index){

        if(confirm('Deseja realmente remover a categoria "' + $scope.categories[index].Name + '"?'))
        {

            $scope.loading = true;

            var toremove = $scope.categories[index];

            Categories
            .deleteCategory(toremove.Id)
            .success(function(data){
                $scope.addAlert(toremove.Name + ' removida com sucesso','success');
                $scope.categories.splice(index, 1);
                $scope.loading = false;
            }).
            error(function(error){
                if(!!error)
                    $scope.addAlert(error.ExceptionMessage, 'danger');
                else
                    $scope.addAlert('Não foi possível remover a categoria, verifique a disponibilidade do serviço', 'danger');
                $scope.loading = false;
            });
        }

    };


 });

我希望这有帮助

见你。