AngularJSに、ng-ifディレクティブを持つトップHTML要素を表示しないように指示する方法はありますか?私はAngularに子コンテンツだけを表示させたいのです。
Angularコード:
<div ng-if="checked" id="div1">
<div id="div2">ABC</div>
<div id="div3">KLM</div>
<div id="div4">PQR</div>
</div>
レンダリングされた HTML:
<div id="div1">
<div id="div2">ABC</div>
<div id="div3">KLM</div>
<div id="div4">PQR</div>
</div>
私が欲しいもの:
<div id="div2">ABC</div>
<div id="div3">KLM</div>
<div id="div4">PQR</div>
#div1
は必要ありません。ただ、checked
がtrue
の場合、#div2,3,4
が欲しいだけです。
解決策としては、すべての子要素にng-ifを追加することができますが、私はこれを実行したくありません。
もし、カスタムディレクティブを作成してもいいのであれば、プログラム的にng-ifを子に適用し、その過程でDOMを平坦化することができます。
ディレクティブコード:
.directive('ngBatchIf', function() {
return {
scope: {},
compile: function (elm, attrs) {
// After flattening, Angular will still have the first element
// bound to the old scope, so we create a temporary marker
// to store it
elm.prepend('<div style="display: none"></div>');
// Flatten (unwrap) the parent
var children = elm.children();
elm.replaceWith(children);
// Add the ng-if to the children
children.attr('ng-if', attrs.ngBatchIf);
return {
post: function postLink(scope, elm) {
// Now remove the temporary marker
elm.remove();
}
}
}
}
})
Angular Code:
<div id="div1" ng-batch-if="checked">
<div id="div2">ABC</div>
<div id="div3">KLM</div>
<div id="div4">PQR</div>
</div>
レンダリングされた HTML:
<div id="div2" ng-if="checked">ABC</div>
<div id="div3" ng-if="checked">KLM</div>
<div id="div4" ng-if="checked">PQR</div>
フィドル:
親Divを使いたくない理由はわかりませんが、+20個のDivがある場合は良い解決策になると思います。
HTML
<div ng-repeat="div in divs" ng-if="checked" id="{{div.name}}">{{div.content}}</div>
JS
app.controller('myCtrl', function($scope) {
$scope.checked = true;
$scope.divs = {
{'name': 'div2', content:'ABC'},
{'name': 'div3', content:'KLM'},
{'name': 'div4', content:'PQR'}
}
});
div1は
div2,div3,div4の親コンテナなので、
div1` を出力 html に表示したくない場合は、これを使用します:-)
<div ng-app="App">Click me:
<input type="checkbox" ng-model="checked" ng-init="checked=true" />
<br/>Show when checked:
<div class="div2" ng-if="checked">ABC</div>
<div class="div3" ng-if="checked">KLM</div>
<div class="div4" ng-if="checked">PQR</div>
</div>
編集:-
そのグループに属するすべての要素に共通のクラス(例:myClass
)を割り当てる。
JS:-
angular.module('App', []);
function myController($scope) {
$scope.change = function () {
angular.element(".myClass").toggle();
};
}
HTML:-
<div ng-app="App" ng-Controller="myController">Click me:
<input type="checkbox" ng-change="change()" ng-model="checked" ng-init="checked=true" />
<br/>Show when checked:
<div id="div2" class="myClass">ABC</div>
<div id="div3" class="myClass">KLM</div>
<div id="div4" class="myClass">PQR</div>
</div>