访问ngRepeat范围

时间:2014-03-04 20:23:24

标签: angularjs

当用户单击同级按钮时,我想清除附加到ngRepeat范围的文本框属性。你会怎么做?

ngRepeat似乎没有暴露其范围..否则我会传递addCustomCheckbox函数。

部分

<div ng-repeat="template in currentUser.templates">

        <div class="form-group">
            <h4>Custom Checkboxes</h4>
            <ul class="list-group">
                <li ng-repeat="cc in template.customCheckboxes" class="list-group-item">{{cc}}</li>
            </ul>
            <input type="text" ng-model="newCustomCheckboxName"/>
            <button ng-click="addCustomCheckbox(template,newCustomCheckboxName)" class="btn btn-primary">Add Checkbox</button>
        </div>
</div>

控制器

$scope.addCustomCheckbox = function(template,checkboxName){
    if(checkboxName==="") return;

    if(_.find(template.customCheckboxes,checkboxName)===undefined){
        template.customCheckboxes.push(checkboxName);
        //todo: clear ngRepeatScope newCustomCheckboxName here.
    }

}

1 个答案:

答案 0 :(得分:1)

尝试扭转你的想法。不要考虑如何访问ng-repeat中的范围,而是考虑如何将要访问的数据移动到 范围。

假设你的$ scope包含这个ng-repeat,它有一个名为'model'的$ scope属性($ scope.model)。然后,我们可以在$ scope.model对象上设置输入模型,而不是将其留在ng-repeat范围内的对象上。

我的例子假设'cc'对于每次迭代都是唯一的。

<div ng-repeat="template in currentUser.templates">

        <div class="form-group">
            <h4>Custom Checkboxes</h4>
            <ul class="list-group">
                <li ng-repeat="cc in template.customCheckboxes" class="list-group-item">{{cc}}</li>
            </ul>
            <input type="text" ng-model="model[cc]"/>
            <button ng-click="addCustomCheckbox(template,cc)" class="btn btn-primary">Add Checkbox</button>
        </div>
</div>

$scope.addCustomCheckbox = function(template,cc){
    var data = $scope.model[cc];
    if(data==="") return;

    if(_.find(template.customCheckboxes,data)===undefined){
        template.customCheckboxes.push(data);
        $scope.model[cc] = "";
    }

}