控制器的指令范围

时间:2016-01-11 18:39:15

标签: angularjs twitter-bootstrap

我已经创建了一个指令,因此我可以在成功事件中使用控制器中的函数关闭bootstrap-modal。我试过的是

//Directive
.directive('modalBox', function() {
    return {
        restrict: 'C',
        link: function(scope, element) {
            console.log(element);
            scope.dismiss      = function() {
                element.modal('hide');
            };
            scope.dismissModal = function(inputClass) {
                $('.' + inputClass).modal('hide');
            };
        }
    };
});

HTML就像

<div id="myModal" data-backdrop="static" class="modal fade modalBox myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-xlg">
    <div class="modal-content">
        <div class="modal-header modal-header-danger">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="margin-none" ng-if="!operation">Add Fuel Entry</h4>
            <h4 class="margin-none" ng-if="operation">Update Fuel Entry</h4>
        </div>
        <div class="modal-body">My Form Data
 </div>
    </div>
</div>

并且在控制器中我实现它像 -

$scope.closeModal = function() {
      $scope.dismissModal('myModal'); 
};

它给了我undefined的错误。我在哪里做错了。

1 个答案:

答案 0 :(得分:1)

如果要创建指令,则应在指令中绑定此closeModal方法。当你使用bootstrap的模态形式时,你也应该考虑使用angular-bootstrap组件。

对于这种特定情况,您可以删除此指令并直接在控制器上与模态进行交互:

HTML:

<div id="myModal" data-backdrop="static" class="modal fade modalBox myModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xlg">
        <div class="modal-content">
            <div class="modal-header modal-header-danger">
            <button type="button" class="close" ng-click="closeModal('myModal') aria-hidden="true">×</button>
            <h4 class="margin-none" ng-if="!operation">Add Fuel Entry</h4>
            <h4 class="margin-none" ng-if="operation">Update Fuel Entry</h4>
         </div>
      <div class="modal-body">My Form Data
      </div>
    </div>
</div>

并在您的控制器上:

$scope.closeModal = function(modalId) {
  $("#" + modalId).modal('hide');
};