gpt4 book ai didi

javascript - Angularjs-UI Bootstrap : Accordion Open and close all

转载 作者:行者123 更新时间:2023-12-03 06:53:11 29 4
gpt4 key购买 nike

我编写了一些代码来打开和关闭 Accordion 的所有选项卡,分别使用单独的“打开”和“关闭”按钮。它如何要求我动态地将键值对( bool 值)添加到我的 json 数据中。

这种情况下的最佳做法是什么?我应该将 bool 值添加为静态 json 元素,还是可以在其唯一目的是用于视觉结构且与实际对象数据无关时动态添加值。

HTML/Angular 指令

<div id="app" ng-app="demoApp">
<div id="controller" ng-controller="demoAppCtrl">
<uib-accordion close-others="false">
<div class="btn-group form-group">
<button type="button" class="btn btn-warning" ng-click="toggle(true)">Open</button>
<button type="button" class="btn btn-warning" ng-click="toggle(false)">Close</button>
</div>
<uib-accordion-group is-open="hero.state" ng-click="setOpened(false)" ng-repeat="hero in heroes">
<uib-accordion-heading>
{{hero.name}}
</uib-accordion-heading>
{{hero.bio}}
</uib-accordion-group>
</uib-accordion>
</div>
</div>

Javascript/Angular

var app = angular.module('demoApp', ['ngAnimate','ui.bootstrap']);
app.controller('demoAppCtrl', function($scope) {

// This json object contain only one entry as an example
$scope.heroes = [
{'name': 'Captain America', 'team': 'Avengers', 'bio': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae metus placerat, condimentum nisl et, accumsan sapien. Quisque molestie magna nulla, id malesuada sem interdum a.'}
];

$scope.addDefaultState = function(val) {
for (var i=0;i<$scope.heroes.length;i++) {
$scope.heroes[i].state = val;
}
}
$scope.addDefaultState(false);

$scope.toggle = function(status) {
$scope.heroes.forEach(function(e) {
e.state = status;
});
}

});

codepen.io - Working example (with corrections)

最佳答案

在我看来,静态 json 不应包含 bool 状态值。动态添加值以进行视觉呈现是可以的。

在您的代码中,不需要函数addDefaultStateis-open="hero.state" 将处理默认状态,因为最初它不会找到状态并将其视为 false。因此,您像下面这样更改代码,它也应该可以工作:

var app = angular.module('demoApp', ['ngAnimate','ui.bootstrap']);
app.controller('demoAppCtrl', function($scope) {

// This json object contain only one entry as an example
$scope.heroes = [
{'name': 'Captain America', 'team': 'Avengers', 'bio': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae metus placerat, condimentum nisl et, accumsan sapien.'}
];

$scope.toggle = function(status) {
$scope.heroes.forEach(function(e) {
e.state = status;
});
}

});

关于javascript - Angularjs-UI Bootstrap : Accordion Open and close all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37409669/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com