检查来自控制器

时间:2015-11-02 18:48:22

标签: angularjs angularjs-ng-repeat

我是angularjs的新手。我的模板是这样的:

<div ng-repeat="item in values"></div>
<div ng-repeat="item1 in values1"></div>

我的控制员:

$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
         $scope.values = data;
    });
};

工作正常。现在我想显示这些项目,只有它是空的。

我试过这样的事情:

$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
    if ($scope.values.length == 0) {
         $scope.values = data;
    } else {
         $scope.values1 = data;
    }
    });
};

任何想法如何从控制器检查是否有ng-repeat有数据?

提前致谢

2 个答案:

答案 0 :(得分:1)

确保您在顶部初始化数组,然后您可以执行以下操作:

 //initialize vars
 $scope.values = [];
 $scope.values1 = [];


$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
    if ($scope.values.length === 0) {
         //you may or may not want to clear the second array if you are toggling back and forth
         $scope.values1 = [];
         $scope.values = data;
    } else {
         //empty the first one so we make the hide/show logic simple
         $scope.values = [];
         $scope.values1 = data;
    }
    });
};

然后你的html看起来像

<div ng-show="values.length" ng-repeat="item in values"></div>
<div ng-show="values1.length" ng-repeat="item1 in values1"></div>

以下是概念的快速证明 - http://jsfiddle.net/Lzgts/573/

如果你想让div实际上从DOM中删除,你也可以用ng-if交换ng-show。

答案 1 :(得分:0)

根据你的数组的初始化方式(我们没有看到),它可能永远不会有长度== 0(例如我认为它可能是未定义的等等)你可以尝试:

if ($scope.values.length != 0) {
        $scope.values1 = data; 
    } else {
        $scope.values = data;
    }