避免在Angular控制器中重复

时间:2015-03-26 18:21:38

标签: angularjs ionic-framework

我是一个有角度的新手,我正在写一个离子应用程序。 我完成了我的应用程序,并试图重构我的控制器,避免重复代码。

我有这段代码来管理我的模态:

 angular.module('starter')
  .controller('NewsCtrl', function($scope, content, $cordovaSocialSharing, $timeout, $sce, $ionicModal){
    $scope.news = content;

    content.getList('comments').then(function (comments) {
      $scope.comments = comments;
    });

    $scope.addComment = function() {

    };

    $scope.shareAnywhere = function() {
        $cordovaSocialSharing.share("Guarda questo articolo pubblicato da DDay", "Ti stanno segnalando questo articolo", content.thumbnail, "http://blog.nraboy.com");
    };

    $ionicModal.fromTemplateUrl('templates/comments.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });

    $scope.showComment = function() {
      $scope.modal.show();
    };

    // Triggered in the login modal to close it
    $scope.closeComment = function() {
      $scope.modal.hide();
    };

    $scope.$on('modal.shown', function() {
      var footerBar; 
      var scroller;
      var txtInput;

      $timeout(function() {
        footerBar = document.body.querySelector('#commentView .bar-footer');
        scroller = document.body.querySelector('#commentView .scroll-content');
        txtInput = angular.element(footerBar.querySelector('textarea'));
      }, 0);

      $scope.$on('taResize', function(e, ta) {        
        if (!ta) return;   
        var taHeight = ta[0].offsetHeight;        
        if (!footerBar) return;
        var newFooterHeight = taHeight + 10;
        newFooterHeight = (newFooterHeight > 44) ? newFooterHeight : 44;

        footerBar.style.height = newFooterHeight + 'px';
        scroller.style.bottom = newFooterHeight + 'px'; 
      });

    });

  });

我在6个控制器中添加了相同的代码。 有没有办法避免重复?

2 个答案:

答案 0 :(得分:1)

您正在寻找的是角度服务。该组件是一个单例对象,您可以在执行此代码所需的每个控制器中注入该组件。

Angular Services

此致

答案 1 :(得分:0)

下面是我创建的用于从Json文件检索地址数据的服务示例。这是工作的Plunk。 http://plnkr.co/edit/RRPv2p4ryQgDEcFqRHHz?p=preview

  angular.module('myApp')
    .factory('addressService', addressService);

  addressService.$inject = ['$q', '$timeout', '$http'];

  function addressService($q, $timeout, $http) {
    var addresses = [];

    //console.log("Number of table entries is: " + orders.length);

    var promise = $http.get('address.data.json');
    promise.then(function(response) {
      addresses = response.data;
      //  console.log("Number of table entries is now: " + orders.length);
    });

    return {
      GetAddresses: getAddresses
    };

    function getAddresses() {

      return $q(function(resolve, reject) {
        $timeout(function() {
          resolve(addresses);
        }, 2000);

      });

    }
  }

以下是我如何为其添加依赖项以及向控制器添加其他服务的示例(这不是执行依赖项注入的唯一方法,但这是我最喜欢的方式,因为它更容易阅读)。然后我从我的控制器中调用了addressService.GetAddresses()

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

app.controller('TableController', TableController);

TableController.$inject = [ "orderService",  "addressService"];

function TableController( orderService, addressService) {

 addressService.GetAddresses()
  .then(function(results) {
      me.addresses = results;
     // console.log(me.addresses.length + " addresses");
    },
    function(error) {})
  .finally(function() {
    me.loadingAddresses = false;
});
  });}

我还必须在index.html的脚本元素中包含我的.js标记。

<script src="addressdata.service.js"></script>