检查是否已单击ng-click按钮

时间:2015-06-30 23:41:02

标签: javascript arrays angularjs angularjs-scope angularjs-ng-repeat

我使用divng-click isVisible上切换$scope.Objectlist.push(data);。我遇到的问题是,每次单击按钮,它都会运行<tr ng-repeat="object in objectlist"> <td>{{object.id}}</td> <td><button ng-click="pushData(object.id)">View</button></td> </tr> 。我想只在第一次点击时推送它,但同时我希望它在推取其他对象时推送它。我在每一行旁边都有一个按钮,每行都有一个不同的id,它将作为按钮功能的参数传递。

HTML:

$scope.objectlist = [];
$scope.isVisible = false;
$scope.pushData= function(id) {
    $http.get("some variables being passed on here").success(function(data, status, headers, config){
            $scope.objectlist.push(data);
    }).error(function(data, status, headers, config){
        alert("Error");
    });
    $scope.isVisible = ! $scope.isVisible;
};

JS:

self.grid.setSpacing(0)

我有多个不同的对象,有些是空的,有些不是,所以这个函数不能只检查列表的长度

2 个答案:

答案 0 :(得分:4)

如何存储每个对象id的可见性(我没有测试它):

<强> HTML

<tr ng-repeat="object in objectlist">
    <td>{{object.id}}</td>
    <td><button ng-click="pushData(object.id)">View</button></td>
</tr>

<强> JS

$scope.objectlist = [];
$scope.isVisible = false;
var store = {}; // Store visibility (boolean) per object id

$scope.pushData= function(id) {
    // If not stored yet
    if (!store[id]) {
        $http.get("some variables being passed on here").success(function(data, status, headers, config){
            $scope.objectlist.push(data);
            store[id] = true; // Store it and set true for the visibility
        }).error(function(data, status, headers, config){
            alert("Error");
        });
    }
    $scope.isVisible = !store[id]; // Set the visibility depending on if the object is already in the store or not
};

我不确定$scope.isVisible = !store[id];,因为我真的不知道它在视图中的交互。但类似的东西可以做到这一点

答案 1 :(得分:2)

试试这个,

$scope.objectlist = [];
$scope.isVisible = false;
var uniqueIDs = {}; 

$scope.pushData= function(id) {
        $http.get("some variables being passed on here").success(callbackFn)

.error(function(data, status, headers, config){

            alert("Error");
        });

    $scope.isVisible = !uniqueIDs[id];
};



var callbackFn = function(id){
if(!uniqueIDs[id]){
    $scope.objectlist.push(data);
    uniqueIDs[id] = true;

     }
};
相关问题