如何重用在多个控制器功能 [英] how to reuse a function in multiple controllers

查看:108
本文介绍了如何重用在多个控制器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have multiple controllers for multiple routes:

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登录路径1当我们在ROUTE1和FirstController是当前控制器和登录航线2时,路线2,但只有1击溃是我在控制台中看到。可以请你告诉我,为什么改变路线不会改变指令的适用范围$?

$scope.func is different in each controller. I expect the $scope.func to log "route 1" when we are in route1 and FirstController is the current controller and to log "route 2" when in route 2, but only "rout 1" is what I get in console. may you please tell me why changing route doesn't change $scope of directive?

推荐答案

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

Isolated Scope was what I used for reusing a function which is defined differently is multiple controllers.
according to docs, when you isolate the scope of directives like:

scope: {
  myIsolatedFunc: '='
}

角将查找当前范围的名为 myIsolatedFunc 元素的属性值属性。这意味着:

Angular will look up the current scope for a property named as the value of myIsolatedFunc property of element. meaning that:

如果您有 $ scope.func1 定义为一个名为功能和元素:

if you have a function named $scope.func1 and an element defined as:

<div myIsolatedFunc="func1">

和在其他的路线的另一个控制器与元素一起像 $ scope.func2 函数定义为:

and in another route with another controller a function like $scope.func2 along with an element defined as:

<div myIsolatedFunc="func2">

您可以在一个指令同时使用的功能:

you can use both of the functions in a directive:

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

何况没有必要具有用于不同功能的不同的名称。

not to mention there is no need to have different names for different functions.

这篇关于如何重用在多个控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆