带有编译函数和ng-show的角度对话框指令不起作用

Angular dialog directive with compile function and ng-show does not work

本文关键字:对话框 指令 不起作用 ng-show 编译 函数      更新时间:2023-09-26

受本文启发,我创建了一个对话框指令。但我想更灵活一点(例如,不要为每个对话框手动在控制器中创建新的变量/函数。我还想在对话框中没有范围,因为对话框中的其他角度组件不会像不在对话框中那样工作。

所以我想到了这个:

angular.module('directives.dialog', [])
.directive('modalDialog', function() {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    compile: function(element, attrs) {
       var html = "<div class='ng-modal' ng-show='" + attrs.dialogid + "'><div class='ng-modal-overlay' ng-click='hideModal" + attrs.dialogid + "()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'> <div class='ng-modal-close' ng-click='hideModal" + attrs.dialogid + "()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
       var newElem = $(html);
       element.replaceWith(newElem);
       return function(scope, element, attrs) {
          //link function
          scope[attrs.dialogid] = false; //don't show in the beginning
          scope['hideModal'+attrs.dialogid] = function() {
            scope[attrs.dialogid] = false;
          };
      }
    }
};
});

用法如下:

<button ng-click="toggleModal('myDialog')">Play weather god</button>
<modal-dialog dialogId='myDialog'>
      <p>Some dialog content<p>
      Other components..
      <div ng-bind="tempValue"></div>
</modal-dialog>

toggleModal在我的控制器中非常简单:

$scope.toggleModal = function(id) {
        $scope[id] = !$scope[id];
};

我的问题是ng-show没有效果,即使dialogId是通过链接函数在作用域中设置的(切换也可以,但正如我所说,它没有效果)。此外,动态生成的隐藏函数也在作用域中。

我有一种感觉,这种方法普遍存在一些问题。你能给出错误可能在哪里或如何做得更好的提示吗?

您需要编译html标记,以便使angular指令生效。

代码中:

您需要首先注入$compile服务:

.directive('modalDialog', function($compile) {...});

然后,您可以使用它来编译这样的标记:

var html = "<div ... ng-show='" + attrs.dialogid + "'> ..."
var newScope = scope.$new();
var newElem = $compile(html)(newScope);
element.replaceWith(newElem);

您可以使用newScope属性将任何变量传递给已编译的标记。例如

var newScope = scope.$new();
newScope.prop1 = 'test';

可以使用"prop1"在模板内部访问。