ng-show isArray表达式

时间:2018-04-05 14:52:23

标签: javascript html angularjs

我想仅在模型字段为数组时才呈现select标记。我有这段代码:

HTML:

<div ng-app>
  <div ng-controller="showCrtl">
        <button class="" ng-click="showCon()">Button1</button>   
        <select ng-show="isArray(tabObj.foo)" ng-model="tabObj.foo" ng-options="x for x in tabObj.foo"></select>
        <span ng-if="!isArray(tabObj.foo)">{{tabObj.foo}}</span>
    </div>
</div>

JS:

function showCrtl($scope){
    $scope.showCon=function(){
        $scope.tabObj={'foo':['AA','BB']};
        alert("is field is Array? "+Array.isArray($scope.tabObj.foo));
    }
}

演示:http://jsfiddle.net/8Yz7S/722/

如您所见,点击按钮后,我只获得span tabObj.foo作为文字。 如何获得select代码?

如果我将tabObj.foo值更改为简单字符串('abc')并使用ng-show="tabObj.foo.length > 0",请检查我始终获得select标记(不要看span) - 请参阅http://jsfiddle.net/8Yz7S/726/

3 个答案:

答案 0 :(得分:2)

这是你必须定义的更新的jsfiddle isArray

http://jsfiddle.net/8Yz7S/732/

function showCrtl($scope){
    $scope.showCon=function(){
        $scope.tabObj={'foo':['AA','BB']};
        $scope.isArray = angular.isArray;
        alert("is field is Array? "+Array.isArray($scope.tabObj.foo));
    }
}

答案 1 :(得分:2)

你的ng-show="isArray(tabObj.foo)"在html中的效果并不像这样。您可以再创建一个变量并检查其值。

&#13;
&#13;
function showCrtl($scope){
$scope.test=false;
    $scope.showCon=function(){
           $scope.tabObj={'foo':['AA','BB']};
           $scope.test=Array.isArray($scope.tabObj.foo);
           alert("is field is Array? "+$scope.test);
    }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="showCrtl">
            <button class="" ng-click="showCon()">Button1</button>   
            <select ng-if="test" ng-model="tabObj.foo" ng-options="x for x in tabObj.foo">
            </select>
            <span ng-if="!test">{{tabObj.foo}}</span>
    </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我希望这会对你有所帮助。谢谢。

function showCrtl($scope){
$scope.isArrayCheck = angular.isArray;
    $scope.showCon=function(){
        $scope.tabObj={'foo':['AA','BB']};  
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="showCrtl">
            <button class="" ng-click="showCon()">Button1</button>   
            <select ng-show="isArrayCheck(tabObj.foo)" ng-model="tabObj.foo" ng-options="x for x in tabObj.foo">
           
            </select>
            <span ng-if="!isArray(tabObj.foo)">{{tabObj.foo}}</span>
    </div>
</div>