通过指令传递信息

时间:2014-06-03 09:31:06

标签: javascript jquery angularjs angularjs-directive

我正在使用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按钮时,我想要显示popUp(为此我使用带有下面指令的jQuery插件。

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

我尝试添加一个需要控制器共享的require,但是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();
                    }
                }); 
            })
        }
    }
});

我的方式错了吗?你有什么建议我做的?

1 个答案:

答案 0 :(得分: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

相关问题