将其转换为服务或工厂,以在不同控制器之间共享功能

时间:2016-01-30 23:37:22

标签: angularjs

我有这个控制器,它包含一个函数,它接受输入名称(fullname)并将其拆分为fname(名字)和lname(姓氏)。 我想将该功能与该控制器分开,以便我可以在控制器之间共享它。不知道怎么做。

appControllers.controller('ContactCtrl', ['$scope', function ($scope) {
$scope.page.setDirection('none');
$scope.splitName = function (fullName) {
  var formData = {},
      nameArr = fullName.split(' ');
  if (nameArr.length == 1) {
    formData.first_name = nameArr[0];
    formData.last_name = '';
  } else if (nameArr.length > 2) {
    formData.last_name = nameArr.pop();
    formData.first_name = nameArr.join(' ');
  } else {
    formData.first_name = nameArr[0];
    formData.last_name = nameArr[nameArr.length - 1];
  }
  return formData;
};
$scope.change = function () {
  var newName = $scope.splitName($scope.contact.NAME);
  $scope.contact.FNAME = newName.first_name;
  $scope.contact.LNAME = newName.last_name;
};
//$scope.data = {
//  full_name: 'Joe Middle Name Smith',
//  first_name: '',
//  last_name: '',
//}
//var example = $scope.splitName($scope.data.full_name);
 }
]);

1 个答案:

答案 0 :(得分:0)

步骤相当容易。

将相同的功能移至工厂并返回对它的引用。

在需要访问它的组件中注入工厂。

然后使用ServiceName.ServiceMethod()

而不是使用范围引用函数
appControllers.controller('ContactCtrl', ['$scope','Utilities', function ($scope, Utilities) {
    $scope.page.setDirection('none');

    $scope.change = function () {
        // use new factory method
        var newName = Utilities.splitName($scope.contact.NAME);
        $scope.contact.FNAME = newName.first_name;
        $scope.contact.LNAME = newName.last_name;
    };
}
]);

angular.module('myApp').factory('Utilities', function(){
    function splitName (fullName) {
        var formData = {},
                nameArr = fullName.split(' ');
        if (nameArr.length == 1) {
            formData.first_name = nameArr[0];
            formData.last_name = '';
        } else if (nameArr.length > 2) {
            formData.last_name = nameArr.pop();
            formData.first_name = nameArr.join(' ');
        } else {
            formData.first_name = nameArr[0];
            formData.last_name = nameArr[nameArr.length - 1];
        }
        return formData;
    }
    // return object with any factory properties needed
    return {
        splitName : splitName
        // add more properties as needed to expand functionality of factory
    }

})