gpt4 book ai didi

javascript - 在 Angular js Getters 中传递参数

转载 作者:行者123 更新时间:2023-12-03 03:55:36 24 4
gpt4 key购买 nike

我使用的是 Angular 1.6.x

我有一个复选框列表,它们使用变量(selectedJobIds)维护其状态。该变量包含选定的作业 ID,例如,

$scope.selectedJobIds = {
23: true,
56: true,
47: false
}

现在,我需要检查该对象中存在且值为 true 的复选框。此外,即使对象中不存在复选框,也应该选中它们。

目前,它无法区分不存在的 id 和具有 false 值的 id。它取消选中它们。

尝试过的方法:1)我尝试实现三元条件ng-model="(angular.isDefined(selectedJobIds[job.iid])?selectedJobIds[job.iid]:true)"

但它会抛出语法错误。

2) 我尝试使用 ng-model-options 的 getter/setter但问题是我无法将作业 ID 传递给 getter 函数。另外,我无法获取当前元素的范围,因此我可以访问它的值。因此,我可以使用这个 id 来检测它在 selectedJobIds 变量中是否存在。

HTML:

<ul class="list-unstyled filtered-trucks-ul">
<li ng-repeat="job in dType track by $index" style="vertical-align: middle;">
<input type="checkbox" name="job_id" value="{{job.iid}}"
ng-click="selectFilterJob()"
ng-model="selectedJobIds[job.iid]" />
<img src="23.png">
{{ job.rref + ' (' +job.iid+ ')' | uppercase }}
</li>
</ul>

JS:

$scope.checkedFilteredJobs = {
getterFunc: function(newName) {
console.log(newName)
// if(angular.isDefined($scope.selectedJobIds[id]))
// {
// return $scope.selectedJobIds[id];
// }
// else {
return true;
// }
}
};

最佳答案

使用 ng-init 初始化缺失的属性:

var app = angular.module('myApp', []);

app.controller('myAppController', ['$scope', function($scope) {

$scope.dType = [{iid: 23}, {iid: 56}, {iid: 47}, {iid: 1234}, {iid: 888}];
$scope.selectedJobs = {
23: true,
56: true,
47: false
};

$scope.initMissing = function(job) {
if (!$scope.selectedJobs.hasOwnProperty(job.iid))
$scope.selectedJobs[job.iid] = true
}

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="myAppController">
<ul>
<li ng-repeat="job in dType track by $index">
<input type="checkbox" ng-init="initMissing(job)" name="job_id"
ng-model="selectedJobs[job.iid]" />
</li>
</ul>
</div>

关于javascript - 在 Angular js Getters 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967612/

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