Angular ng-repeat忽略嵌套的ng-if

时间:2015-09-11 16:12:41

标签: javascript angularjs

Howdie do,

如果客户端用于登录的代码与控制器中的$ scope.code匹配,我试图只显示一个选项。

然后,HTML应显示与客户端登录的代码匹配的选项。

查看:

<div class="">
<select id="customer-dd" ng-model="selectedCustomer" ng-repeat="(group, msg) in codes">
    <option value="">select...</option>
            <div ng-if=" 'group' == 'code' ">
                 <option value="{{ group }} ">{{ msg }}</option>
             </div>
</select>
</div>

控制器:

$scope.code = dataFactory.getCode();
$scope.codes = {

 'ABC': 'First option',
 'DEF': 'Second option'
}

只应显示一个选项,因为客户端无法一次登录多个代码

然而,当我运行它时,我不断获得两个输入框,而不仅仅是匹配代码的输入框。

这里有什么我想念的吗?

*更新*

我已将代码更新为以下内容,并且仍在打印多个选项:

<div class="">
<select id="customer-dd" ng-model="selectedCustomer" ng-repeat="(group, msg) in codes">
    <option value="">select...</option>
        <div ng-if=" group == code ">
            <option value="{{ group }} ">{{ msg }}</option>
        </div>
</select>
</div>

*更新* @ieaglle删除div允许if语句执行。更新的HTML现在是:

<div class="">
<select id="customer-dd" ng-model="selectedCustomer" ng-repeat="(group, msg) in codes">
    <option value="">select...</option>
    <option ng-if=" group == code " value="{{ group }} ">{{ msg }}</option>
</select>
</div>

THANKKKK UUUU !!!

2 个答案:

答案 0 :(得分:1)

尝试使用ng-options代替过滤后的对象。

http://jsfiddle.net/joshdmiller/hb7lu/

HTML:

<select ng-model="selectedCustomer" ng-options="msg for (group, msg) in filterObjsByProp(codes)"></select>

JS:

$scope.code = 'ABC';
$scope.codes = {

    'ABC': 'First option',
        'DEF': 'Second option'
};

$scope.filterObjsByProp = function (items) {
    var result = {};
    angular.forEach(items, function (value, key) {
        if (key === $scope.code) {
            result[key] = value;
        }
    });
    return result;
}

虽然这有点过分,但由于对象不能具有多个具有相同名称的属性,因此您在select中只能有1个选项。因此,这里的select可能不是最佳选择,或者带有键/值对象的数组可能更好。

答案 1 :(得分:0)

将HTML更改为此。 请注意ng-if语句中的更改。

<div class="">
<select id="customer-dd" ng-model="selectedCustomer">
    <option value="{{ group }}" ng-repeat="(group, msg) in codes">select...
            <div ng-if=" group == code ">
                {{ msg }}
             </div>
    </option>
</select>
</div>