2014-12-04 63 views
0

我已經使用指令來利用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的冗餘。所以我希望指令具有自己的關閉功能。如果您對上述其他問題也有答案,非常感謝。謝謝。

回答

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> 
+0

'element.dialog()'會調用彈出窗口嗎? – menorah84 2014-12-04 02:44:25

+0

這只是調用最簡單的jQueryUI對話框API。用你需要的替代它。 – user2943490 2014-12-04 02:48:00

+0

如何在此指令之外調用'element.dialog()'?像在外部控制器中一樣? – menorah84 2014-12-04 03:03:29