AngularJS 通过 function() 调用显示/隐藏

标签 angularjs angularjs-scope

是否可以在返回 bool 值的函数调用后显示/隐藏元素?场景是,当所有 n 项都有“同意”标志时显示“就绪”。如果没有,请展示其他东西。使用单选按钮更改商定标志的值。

$scope.data = [
    {
        title: "Agreement #1",
        agreed: false,
    },
    {
        title: "Agreement #2",
        agreed: false,
    },
];

$scope.ready = function()
{
    var go = true;
    angular.forEach($scope.data, function(item, key) {
        go &= item.agreed==true;
      });
    return go;
}

然后,调用:

<div ng-show="ready()">Go!</div>
<div ng-hide="ready()">Missing the points.</div>

此代码存在问题:如果选中所有单选按钮,即。同意标志的所有值都设置为 true,ready() 不会自动更新。

最佳答案

您可以将agreement的 bool 值绑定(bind)到单选按钮的ng-model,并使用ng-value为每个协议(protocol)设置true/false。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [
    {
        title: "Agreement #1",
        agreed: false,
    },
    {
        title: "Agreement #2",
        agreed: false,
    }
]

$scope.ready = function()
{
    var go = true;
    angular.forEach($scope.data, function(item, key) {
        go &= item.agreed==true;
      });
    return go;
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<div ng-show="ready()">Go!</div>
<div ng-show="!ready()">Missing the points.</div>
    <table>
        <tr>
            <th>Agreement </th>
            <th>Status</th>
        </tr>
        <tr ng-repeat="value in data">
            <td>{{value.title}}</td>
            <td>
                Yes <input type="radio" ng-model="value.agreed" ng-value="true" />
                No <input type="radio" ng-model="value.agreed" ng-value="false"  />
            </td>
        </tr>
    </table>
   
    
    <span>{{data}}</span>
</div>
</body>
</html>

关于AngularJS 通过 function() 调用显示/隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536015/

相关文章:

angularjs - 为什么我无法访问正确的范围?

angularjs - 在 Angular 中修改数组不起作用

javascript - Angular JS 应用程序无法通过 Wcf 服务从 Sql 数据库检索数据

javascript - 在 AngularJS 中重新评估定时器过滤器

angularjs - 如何使用Angular-Material获得全高sidenav

angularjs - html 数据列表不支持 ng-options : how to pass object

javascript - 如何将表单字段的值设置为 JSON 中的值?

angularjs - ng-if 导致 $parent.$index 被设置为 $index

javascript - 如何测试一个对象是否是 Angular 范围?

javascript - 让 Angular $interval 独立于 Controller 运行