【问题标题】:AngularJS, activate checkboxes before ng-model is declaredAngularJS,在声明 ng-model 之前激活复选框
【发布时间】:2016-10-10 07:33:06
【问题描述】:

我正在使用 Angular 开发一个 Web 应用程序,我需要一些与数据库内容相关的复选框,因此我使用 ng-repeat。我想要一个辅助数组来控制 ng 模型,最初所有复选框都必须为真。

我从 ajax 请求中获取数据,但我现在不知道要获取多少元素,所以我不知道会有多少复选框。问题是在 ajax 调用完成之前我不知道辅助数组的大小,到那时复选框已经出现在屏幕上,没有被选中。

我的代码如下:

<div class="checkbox" ng-repeat="c in categories">
    <label for="{{c.id}}" ><input type="checkbox" ng-model="catselection[c.id]">{{c.name}}</label>
</div>

在控制器中我有这个:

$http.get("api.php/categories")
    .success(function(data, status, headers, config){
        $scope.categories = data;
        $scope.catselection = [];
        for(x in $scope.categories){
            $scope.catselection.push("true");
        }
    })
    .error(function (data, status, headers, config) {});

其余的行为是正确的,但我需要在开始时激活复选框,我尝试了 html 属性 checked 甚至 ng-checked 和我知道不推荐使用 ng-model,到目前为止似乎没有任何效果。

【问题讨论】:

  • 您是否尝试过使用 window.onload 事件,以便在文档完成加载后将设置应用于复选框

标签: javascript html angularjs ajax checkbox


【解决方案1】:

你试过ng-init吗?

...
<label for="{{c.id}}" ><input type="checkbox" ng-model="catselection[c.id]" ng-init="catselection[c.id] = true">{{c.name}}</label>
...

【讨论】:

  • 完美运行!我什至可以删除用于填充辅助数组的循环。谢谢!!
【解决方案2】:

不太确定复选框的直接修复,但我会查看&lt;input&gt; 标记的value="" 属性。当我在自己的带有无线电输入的项目中使用value="" 时,只要我更改将无线电输入链接到的ng-model 的值,它就会自动选择正确的无线电输入。 (项目:http://omrin7.github.io/potg/。注意bgImg 是如何设置为“dva”的,它会自动选择它。)

【讨论】:

  • 我看到它对你有用,但它似乎不适用于我的情况。谢谢
【解决方案3】:

创建辅助数组 ($scope.catselection) 后,只需将响应(数据数组)分配给范围变量即可。

$http.get("api.php/categories")
    .success(function(data, status, headers, config){       
        $scope.catselection = [];
        for(x in $scope.categories){
            $scope.catselection.push("true");
        }
     $scope.categories = data;
    }) 

也不要使用 c.id,而是使用 $index。

ng-model ="catselection[$index]"

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多