2013-10-03 37 views
1

我嘗試使用僞指令創建自己的按鈕。 點擊按鈕後,應該僱用對話框(bootstrap.dialog)。 但是,它不會。 嘗試沒有點擊事件,它的作品。單擊元素後無法顯示角度對話框

使用此: - AngularJS v1.0.8 - 引導2.3.2 - 角引導0.3.0

這裏是我的指令......

.directive("ucayButton", function($dialog) { 
    return { 
     restrict: 'EA', 
     template: '<button ng-transclude></button>', 
     replace: true, 
     transclude: true, 
     link: function(scope, element, attrs) { 
      element.addClass('btn btn-primary'); 
      var t = '<div class="modal-dialog">' + 
         '<div class="modal-content">' + 
         '<div class="modal-header">' + 
         '<button type="button" class="close" ng-click="close()" aria-hidden="true">&times;</button>' + 
          '<h4 class="modal-title">Modal title</h4>' + 
         '</div>' + 
         '<div class="modal-body">' + 
          '<p>One fine body&hellip;</p>' + 
         '</div>' + 
         '<div class="modal-footer">' + 
          '<button type="button" class="btn btn-default" ng-click="close()">Close</button>' + 
          '<button type="button" class="btn btn-primary" ng-click="close()">Save changes</button>' + 
         '</div>' + 
         '</div><!-- /.modal-content -->' + 
        '</div><!-- /.modal-dialog -->'; 

      var modalOpts = { 
       backdrop: true, 
       keyboard: true, 
       backdropClick: true, 
       template: t, 
       controller: 'dialogCtrl' 
      }; 

      scope.openDialog = function(){ 
       console.log('confirmation called'); //always shown when function was called 
       var d = $dialog.dialog(modalOpts); 
       d.open().then(function(result){ 
       if(result) 
       { 
        alert('dialog closed with result: ' + result); 
       } 
       }); 
      }; 
      angular.forEach(element, function(el) { 
       el.addEventListener('click', function() { 
       scope.openDialog(); // the function was hired, but the dialog didn't 
       }); 
      }); 
      scope.openDialog(); //hired 
     } 
    }; 
}) 
+0

請發表小提琴或Plunker來幫助我們檢測到問題。謝謝 –

+0

以前感謝。但它已經解決了。^_^ – user2842277

回答

1

addEventListener不是一個角功能,因此當您執行影響$scope變量的代碼時,您需要將這些更改回到摘要循環中。

試試這個:

el.addEventListener('click', function() { 
    if(scope.$$phase) { 
     scope.openDialog(); 
    } else { 
     scope.$apply(function() { 
      scope.openDialog(); 
     }); 
    } 
}); 

這將檢查範圍,如果你是從消化週期內運行的代碼是truthy的$$phase。如果您已經處於摘要循環中,則不需要使用$apply呼叫包裝代碼。如果您沒有在$apply調用中包裝代碼,讓角度知道它需要消化正在進行的更改。

+0

謝謝,皮特。 我已經救了我的一天。 而且,得到了啓發,如何使用$$階段和$ apply。 非常感謝。^_^ – user2842277

+0

快樂。有更多更深入的消化週期和範圍繼承[這裏](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs) 。如果能解決您的問題,請將答案標記爲正確。 :) –

+0

這是一個很好的答案。它應該在角度的文檔^ _ ^ – user2842277