【问题标题】:Check if the ng-click button was clicked already检查是否已经点击了 ng-click 按钮
【发布时间】:2015-09-17 23:04:46
【问题描述】:

我正在使用isVisibleng-click 上切换我的div。我遇到的问题是每次单击按钮时,它都会运行$scope.Objectlist.push(data);。我只想在第一次点击时推送它,但同时我希望它在获取不同对象时推送。我在每一行旁边都有一个按钮,每一行都有一个不同的 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;
$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;
};

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

【问题讨论】:

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


    【解决方案1】:

    如何存储每个对象 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];,因为我真的不知道它在视图中的交互。但是类似的东西可以解决问题

    【讨论】:

    • 出于某种原因,它有时会推送数据,有时却不推送数据......它的错误
    • mmmm...你能设置一个 plunkr 以便更容易调试吗:)
    【解决方案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;
    
         }
    };
    

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多