指令引用自己的id

时间:2014-12-04 02:01:33

标签: angularjs jquery-ui-dialog

我使用了一个指令来使用jqueryUI对话框。

app.directive('popUp', function() {
    return {
        restrict: 'E',
        scope: {
            myId: '@',
            onCancel: '&'
        },
        template: 
            '<div id="{{myId}}">
                <button ng-click="onCancel()">...</button>  
                ...
            </div>' 
        link: function(scope, element, attrs) {
            scope.closeDialog = function() {
                $("#" + id).dialog('close');
            }
            // question 1: how to reference id of this directive (self)?
            // question 2: should it be here, in compile, or in directive controller?
            // question 3: 'ng-click=closeDialog()' missing when popup element inspected in firebug/dev tool
            // question 4: is there a way to avoid jquery like selector $("#" + id) to reference this element?
        }               
    };
});

这是html:

<pop-up my-id="success" on-cancel="closeDialog()"> ... </pop-up> 

如果我声明一个外部控制器并且closeDialog函数附加到其$scope,这样可以正常工作,如下所示:

app.controller('DialogCtrl', function($scope) {

    $scope.closeDialog = function(id) {
        $("#" + id).dialog('close');
    };

});

HTML

<div ng-controller="DialogCtrl">
    <pop-up my-id="success" on-cancel="closeDialog('success')"> ... </pop-up> 
</div>

但我想避免的是id的冗余。所以我希望该指令具有自己的close函数。如果您对上述其他问题也有答案,我们非常感谢。感谢。

1 个答案:

答案 0 :(得分:0)

这基本上就是你想要的。没有必要使用$选择器和id来查找对话框,因为链接函数中的element将为您提供对该指令应用的元素的引用。

在指令范围内定义closeDialog函数,您可以从指令的模板中引用它。该指令的每个实例都有自己的关闭函数。

app.directive('popUp', function() {
    return {
        restrict: 'E',
        scope: {
            myId: '@'
        },
        template: 
            '<div id="{{myId}}">
                <button ng-click="closeDialog()">...</button>
                ...
            </div>' 
        link: function(scope, element, attrs) {
            // initialise dialog
            element.dialog();

            // the template's ng-click will call this
            scope.closeDialog = function() {
                element.dialog('close');
            };
        }               
    };
});

现在不需要取消取消属性。

<pop-up my-id="success"></pop-up>
相关问题