2015-03-31 32 views
0

我正在嘗試使用Angular通過接口管理標籤列表。使用Angular語法刪除陣列中的對象

我有一個服務器拉我的範圍內的標籤列表。

app.js

$scope.Tags = [{id:1, name:'tag1', desc:'desc1'}, {id:2, name:'tag2', desc:'desc2'}, {id:3, name:'tag3', desc:'desc1'}, ...]; 

和我使用的HTML代碼,這個塊顯示列表:

tags.html

<ul> 
<li ng-repeat="T in Tags">{{ T.name }}</li> 
</ul> 

當我點擊<li>元素我想要刪除關聯的Tag對象。 後來我提高我的代碼如下:

tags.html

<ul> 
<li 
    ng-repeat="T in Tags" 
    ng-click="removeTag($event);" 
>{{ T.name }}</li> 
</ul> 

app.js

$scope.removeTag = function (event) { 

    // the following code is just used to remove the Tag from the list 
    // using underscore.js 

    $scope.Tags = _($scope.Tags).filter(function (t) { 
    return t.name !== event.srcElement.innerHTML 
    }); 
} 

這是工作,但我希望有一個較輕的方式執行相同的任務。而且我對Angular的經驗還很有限。

類似的東西將是巨大的:

<ul> 
    <li ng-repeat="T in Tags" ng-click="Tags - T">{{ T.name }}</li> 
    <!-- this is more like a dream tho --> 
</ul> 

回答

1

嘗試拼接基於陣列($index)在索引數組,像這樣:

<ul> 
    <li ng-repeat="T in Tags" ng-click="Tags.splice($index, 1)">{{T.name}}</li> 
</ul> 
+0

這個驚人的作品。有這樣的一些缺點嗎? – user544262772 2015-03-31 16:54:35

+0

@발렌텐唯一的缺點是如果你有其他邏輯運行,而不是簡單地從數組中移除元素(如調用服務器端API)。 – 2015-03-31 16:56:45

+0

@JustinNiessner我沒有,那麼我想這在使用這種語法沒有錯。我喜歡它 – user544262772 2015-03-31 16:57:26

0

Click事件處理程序應該是這樣的:

<ul> 
<li 
    ng-repeat="T in Tags" 
    ng-click="removeTag(T);" 
>{{ T.name }}</li> 
</ul> 

在你的控制器:

$scope.removeTag = function (t) { 
    $scope.Tags.splice($scope.Tags.indexOf(t),1); 
} 

不是傳遞事件對象,我正在傳遞對象本身。

DEMO:

angular.module("app",[]) 
 
.controller("MainCtrl", function($scope) { 
 
$scope.Tags = [{id:1, name:'tag1', desc:'desc1'}, {id:2, name:'tag2', desc:'desc2'}, {id:3, name:'tag3', desc:'desc1'}]; 
 
$scope.removeTag = function (t) { 
 
    $scope.Tags.splice($scope.Tags.indexOf(t),1); 
 
} 
 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 
<head> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body ng-controller="MainCtrl"> 
 
<ul> 
 
<li 
 
ng-repeat="T in Tags" 
 
ng-click="removeTag(T);" 
 
>{{ T.name }}</li> 
 
</ul> 
 
</body> 
 
</html>

0

沒有 「角」 的方式從陣列中刪除項目。您只需要按照常規的舊JavaScript方式進行操作即可。您還可以通過一些簡單的更改來使代碼更清晰。首先,你的標記更改爲:

<ul> 
    <!-- Pass the Tag, not the event --> 
    <li ng-repeat='T in Tags' ng-click='removeTag(T)'> 
     {{ T.name }} 
    </li> 
</ul> 

,然後刪除可以成爲:

$scope.removeTag = function(tag) { 
    var index = $scope.Tags.indexOf(tag); 
    if(index > -1) $scope.Tags.splice(index, 1); 
} 
+0

我認爲你的意思是使用'拼接',而不是'切片' – Kabb5 2015-03-31 16:54:47