javascript - 将元素从链接函数传递到指令内的 Controller 函数,然后再传递给另一个指令

标签 javascript angularjs hyperlink scope directive

是否有一种方法可以将元素从链接函数传递到指令内的 Controller 函数,而不是将其作为元素传递给另一个指令?

我的意思是我有一个指令:

angular.module('myApp').directive('parentDir', function() {
  return {
    restrict: 'E',
    link: function (scope, element, attributes) {
    element = //some HTML code
    },
    controller: function ($scope) {
      this.elem = function () {
        $scope.elem = element;
      }
    }
  }
});

然后我有另一个指令,我想在其中获取 $scope.elem

angular.module('myApp').directive('childDir', function() {
  return {
    restrict: 'E', 
    link: function (scop, elmn, attr){

    // HOW TO GET THE $scope.elem here as elmn ?
    elmn = $scope.elem ?

    }
  }
});

是否可以将 element 传递到 $scope.elem 而不是另一个指令?

编辑:感谢大家的帮助,我还找到了另一种通过 factory under this link 来做到这一点的方法

最佳答案

我认为您正在寻找一种方法让子指令从父指令获取元素。您可以使用指令到指令通信的通用技术来执行此操作,其中子指令可以访问父指令的 Controller :

父目录:

angular.module('myApp').directive('parentDir', function() {
  return {
    restrict: 'E',
    link: function (scope, element, attributes) {
       element = //some HTML code
    },
    controller: function ($scope, $element) {
      this.elem = function () {
          return $element;
      }
    }
  }
});

子指令:

angular.module('myApp').directive('childDir', function() {
  return {
    restrict: 'E', 
    require: '^parentDir',
    link: function (scop, elmn, attr, parentCtrl){    
         var parentElmn = parentCtrl.elem(); 
    }
  }
});

关于javascript - 将元素从链接函数传递到指令内的 Controller 函数,然后再传递给另一个指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31671254/

相关文章:

javascript - 从延迟加载文件延迟加载时出错 - angular.js

javascript - API 调用请求限制为每小时 1 次调用

ios - 可点击的链接(超链接)?

c# - 将光标移到 WPF RichTextBox 中的超链接上?

javascript - 使用 window.open() 打开文件时传递 url 参数(从 ColdFusion 页面)

javascript - HTML5 Canvas 中的平滑行走 Sprite

javascript - 多个日期倒计时脚本

javascript - Angularjs select 未将匹配模型标记为已选择

jquery 从文本链接提交表单

javascript - <script> 标签从输出中删除