如何在多个控制器中重用一个函数

时间:2014-11-19 09:00:36

标签: angularjs angularjs-directive angularjs-service

我有多个路由器的多个控制器:

app.controller('FirstController', function ($scope) {
  $scope.func = function () {
    console.log('route 1');
  }
}
app.controller('SecondController', function ($scope) {
  $scope.func = function () {
    console.log('route 2');
  }
}
...

以及使用$scope.func的指令,这样:

app.directive('thedirective', function () {
  return {
    link: function (scope, $element, attrs) {
      $scope.func(attrs.thedirective);
    }
  }
});

$scope.func在每个控制器中都有所不同。我希望$ scope.func在route1中记录“route 1”,FirstController是当前控制器,在路由2中记录“route 2”,但只有“rout 1”是我在控制台得到的。请你告诉我为什么改变路线不会改变$指令的范围?

2 个答案:

答案 0 :(得分:5)

在AngularJS中,如果函数在控制器中常用。

最佳做法是使用服务或工厂注入控制器。

app.factory('commonService', function ($scope) {
     var obj= {};
      obj.func = function () {
        console.log('route 1');
      }
     obj.func1 = function () {
        console.log('route 2');
      }
  return obj;
    }
    app.controller('FirstController', function ($scope,commonService) { 
        console.log('route 1' + commonService.func());  
    }
    app.controller('SecondController', function ($scope,commonService) { 
        console.log('route 2' + commonService.func1());  
    }

当我们谈论指令时,指令的范围将是一个控制器,无论是指令控制器还是我们定义的外部控制器。

<div ng-controller="firstController">
<your-directive />
</div>

<div ng-controller="secondController">
<your-directive />
</div>

答案 1 :(得分:2)

隔离范围是我用来重用一个不同定义的函数的多个控制器。
根据文档,当你分离指令的范围时,如:

scope: {
  myIsolatedFunc: '='
}

Angular将查找名为element myIsolatedFunc属性值的属性的当前范围。意思是:

如果您有一个名为$scope.func1的函数和一个定义为:

的元素
<div myIsolatedFunc="func1">

并在另一个路径中与另一个控制器一起使用$scope.func2之类的函数以及定义为的元素:

<div myIsolatedFunc="func2">

您可以使用指令中的两个函数:

app.directive('thedirective', function () {
  return {
    scope: {
      myIsolatedFunc: '='
    },
    link: function (scope, $element, attrs) {
      $scope.myIsolatedFunc(attrs.thedirective);
    }
  }
});

更不用说不需要为不同的功能使用不同的名称。