【问题标题】:Passing information through directives通过指令传递信息
【发布时间】:2014-06-03 09:31:06
【问题描述】:

我正在使用 angularJs。

我有这种html:

<body>
<layout>
    <menu>
    </menu>
    <wrappers>
        <article ng-repeat="folder in folders">
                            <!-- some html -->
            <button editFolder="folder.name">
        </article>
    </wrappers>
</layout>
<div myPopUp>
          <input type="text" placeholder="">
          <button ng-click="editFolder()">
</div>
</body>

当用户单击按钮 editFolder 时,我希望显示弹出窗口(为此,我使用带有以下指令的 jQuery 插件。

但我需要将一些特定于单击的按钮范围的值传递给弹出窗口。这是我的问题,我不知道如何在 click 事件上将这些值从一个范围传递到另一个范围。

我尝试添加一个共享控制器的需求,但 div myPopUp 不是另一个的父级...

请注意我无法移动 myPopUp div。

app.directive('editFolder', function() {
    return {
        restrict: 'A',
        template: '<a><img src="img/bt-edit.svg" alt="Modifier"></a>',
        link: function(scope, elem, attrs) {
            elem.bind("click", function(){
                var self = $(this), content = $(''); 
                $(attrs.thePopUp).bPopup({
                    onOpen: function() {
                        content.html(self.data('bpopup') || '');
                    },
                    onClose: function() {
                        content.empty();
                    }
                }); 
            })
        }
    }
});

我是不是走错路了?你建议我做什么?

【问题讨论】:

    标签: javascript jquery angularjs angularjs-directive


    【解决方案1】:

    您可以使用 AngularJS 事件来传递值和启动某些行为。

    • 使用某些值从您想要的位置触发事件。
    • 在 myPopUp 中捕捉事件

      //Catcher in myPopUp
      $rootScope.$on("myEvent", function (event, value1, value2) {
      
      });
      
      //Event firing from custom location
      $rootScope.$broadcast("myEvent", "value1", "value2");
      

    jsFiddle example


    也可以添加一个包含值的父控制器

    <div ng-app="app">
        <!-- hold the values in the parent scope -->
        <div ng-controller="myParent">
            <!-- update the values in the parent scope from child controllers -->
            <!-- + by calling a function in the parent -->
            <!-- + by directly changing the values of the parent -->
            <div ng-controller="myCtrl"></div>
            <!-- link the values for the popup to the parent scope values -->
            <my-pop-up v1="value1" v2="value2"></my-pop-up>
        </div>
    </div>
    

    jsFiddle example

    【讨论】:

    • 它看起来是我需要的,你能给我链接一个文档或一个例子吗?
    • link to api docs for rootScope 每个应用程序都有一个根范围。所有其他作用域都是根作用域的后代作用域。范围通过观察模型变化的机制提供模型和视图之间的分离。他们还提供事件发射/广播和订阅设施。请参阅有关范围的开发人员指南。 因此,使用 $rootScope 没有问题,因为它是所有其他范围的第一个范围。这使得事件在同一个地方观看和收听。
    • 只是不要经常使用事件,因为它会使代码更难调试!
    • 好的,但就我而言,我还有其他选择吗?
    • 是的,但是使用父控制器有点复杂
    猜你喜欢
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多