可重复 DOM 元素上的角度 ng 模型

Angular ng-model on repeatable DOM elements

本文关键字:ng 模型 DOM 元素      更新时间:2023-09-26

是否可以仅使用HTML标记在Angular中定义ng-model范围?

我的标记:

<section>
    <button ng-click="boxOpen = !boxOpen">Open/Close</button>
    <div ng-show="boxOpen">Stuff in here</div>
</section>
<section>
    <button ng-click="boxOpen = !boxOpen">Open/Close</button>
    <div ng-show="boxOpen">Other stuff in here</div>
</section>

上面的问题是"boxOpen"被两者全局解释,因此单击任何一个按钮将同时显示/隐藏两个div。

有什么帮助,谢谢!

如果你定义2个不同的控制器,你会得到两个不同的作用域

<section ng-controller="ctrl1">
     <button ng-click="boxOpen = !boxOpen">Open/Close</button>
     <div ng-show="boxOpen">Stuff in here</div>
</section>
<section ng-controller="ctrl2">
    <button ng-click="boxOpen = !boxOpen">Open/Close</button>
    <div ng-show="boxOpen">Other stuff in here</div>
</section>

您也可以做出指令

.html

<section my-show-hide-dir>
     <button ng-click="boxOpen = !boxOpen">Open/Close</button>
     <div ng-show="boxOpen">Stuff in here</div>
</section>
<section my-show-hide-dir>
    <button ng-click="boxOpen = !boxOpen">Open/Close</button>
    <div ng-show="boxOpen">Other stuff in here</div>
</section>

.JS

     app.directive("myShowHideDir",
    function() {
        return {
            restrict: 'A',
            controller: ['$scope', '$element', '$attrs',
                function($scope, $element, $attrs) {
                    $scope.boxOpen = false;
                }
            ]
        }
    }
);

如果不为此添加单独的控制器(或类似荒谬的事情),您将无法做到这一点。

这里最好的方法是制作这些按钮指令,每个按钮都有自己的隔离作用域......或者,使用两个不同的变量名称,每个按钮一个(如果计划有很多按钮,则将它们放在数组中)。

但我强烈建议采取指令性方法。