如何在多个控制器中重用一个函数 [英] how to reuse a function in multiple controllers

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

问题描述

我有多个控制器用于多条路线:

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

和一个使用 $scope.func 的指令,这样:

app.directive('thedirective', function () {返回 {链接:函数(范围,$element,attrs){$scope.func(attrs.thedirective);}}});

$scope.func 在每个控制器中都不同.我希望 $scope.func 当我们在路由 1 中时记录路由 1",而 FirstController 是当前控制器,并在路由 2 中记录路由 2",但只有路由 1"是我在控制台中得到的.你能告诉我为什么改变路线不会改变指令的 $scope 吗?

解决方案

Isolated Scope 是我用来重用定义不同的函数的方法,它是多个控制器.
根据文档,当你隔离指令的范围,如:

范围:{myIsolatedFunc: '='}

Angular 将查找名为元素的 myIsolatedFunc 属性值的属性的当前范围.意思是:

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

在另一个路由和另一个控制器中,一个类似 $scope.func2 的函数以及一个定义为的元素:

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

app.directive('thedirective', function () {返回 {范围: {myIsolatedFunc: '='},链接:函数(作用域,$element,attrs){$scope.myIsolatedFunc(attrs.thedirective);}}});

更不用说没有必要为不同的功能使用不同的名称.

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');
  }
}
...

and a directive that uses the $scope.func, this way:

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

$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: '='
}

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

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

<div myIsolatedFunc="func1">

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天全站免登陆