gpt4 book ai didi

javascript - 是否可以将 ng-if 与服务值一起使用?

转载 作者:行者123 更新时间:2023-11-30 10:00:48 25 4
gpt4 key购买 nike

我有以下保存一些随机数据的服务

.service('dataSrvc', [function() {
var accountData = {
accounts: [
{
'id': 1,
'title': 'Account A',
'selected': true
},
...

在列表中显示此数据时,如果假设此项目的 id 等于 1,我想添加一个图标。

我试过使用 ng-if

<md-icon aria-label="Duplicates Window" md-font-set="material-icons" ng-if="account.id==1">panorama_fish_eye</md-icon>

但图标从未显示。尝试各种方法,我要么为每个列表项显示图标,要么不显示。

我该如何解决这个问题,并只在需要的地方显示图标。

编辑

对于部分信息,我很抱歉。

这就是我创建列表的方式

<md-sidenav class="site-sidenav md-sidenav-left md-whiteframe-z2"
md-component-id="left"
md-is-locked-open="$mdMedia('gt-sm')" flex>
<md-list ng-controller="listCtrl" class="listControls">

<md-subheader class="md-no-sticky">Possible Duplicate Accounts</md-subheader>
<md-list-item ng-repeat="item in items">
<md-checkbox ng-checked="item.selected" ng-click="toggle(item)"></md-checkbox>
<p>{{item.title}}</p>
<md-icon class="md-secondary" ng-click="doSecondaryAction(item.title, $event)" aria-label="Duplicates Window" md-font-set="material-icons">account_circle</md-icon>
<div flex>
<md-icon aria-label="Duplicates Window" md-font-set="material-icons" ng-if="account.id==1">panorama_fish_eye</md-icon>
</div>
</md-list-item>
</md-list>
</md-sidenav>

这是我的 Controller

.controller('listCtrl', ['$scope', 'dataSrvc', '$mdDialog', function($scope, dataSrvc, $mdDialog) {
$scope.items = dataSrvc.accounts;

$scope.exists = function(item) {
return $scope.items.indexOf(item) > -1;
};

$scope.toggle = function(item) {
item.selected = !item.selected;
};

$scope.doSecondaryAction = function(item, event) {
$mdDialog.show(
$mdDialog.alert()
.title('Data Preview')
.content('Data for ' + item)
.ariaLabel('Duplicates Window')
.ok('Done')
.targetEvent(event)
);
};
}])

最佳答案

在 View 中,您只能引用 Controller 范围内的值。 (即,当您编写 ng-if="account.id===1" 时,它将与 $scope.account 的值匹配)

因此,如果你想在 View 中显示服务值,你必须将它放在 Controller 内的 $scope 中。 (如果你想让这个数据被实时绑定(bind),你应该在 Controller 中使用一个监视表达式,监视服务值)

Matthew Berg 的回答(关于将服务本身绑定(bind)到范围)在性能方面更好(无需花费资源来复制值)- 但这似乎已经是您正在做的事情,请参阅下面我的编辑。


问题编辑后编辑:

看起来你的问题更简单:你的 ng-repeat 为每个 item in items 运行,但是在 ng-if 你引用 account (哪个是服务中相同事物的名称,但不在 ng-repeat 中!)

只需将 ng-if 更改为:

ng-if="item.id==1"

关于javascript - 是否可以将 ng-if 与服务值一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809088/

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