1

我尝试使用指令制作自己的按钮。单击按钮后应使用对话框(bootstrap.dialog)。但是,它不会。在没有点击事件的情况下尝试过,它可以工作。

使用这个: - AngularJS v1.0.8 - Bootstrap 2.3.2 - Angular-bootstrap 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
        }
    };
})
4

1 回答 1

1

addEventListener不是角度函数,因此当您执行影响$scope变量的代码时,您需要将这些更改恢复到摘要循环中。

试试这个:

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

这将检查$$phase范围,如果您在摘要周期内运行代码,这是真实的。如果您已经处于摘要循环中,则无需使用$apply调用包装代码。如果你不是,那么将代码包装在一个$apply调用中,让 Angular 知道它需要消化你所做的更改。

于 2013-10-03T11:21:15.197 回答