我构建了一个动态附加html的指令。我使用$ compile服务将我的ng-click函数添加到作用域,这样我就可以从我的集合中删除项目,但是,它不会从DOM中删除它。它只从集合中删除它。有关如何从集合中删除单个项目并让它相应更新DOM的任何想法吗?
这是我的代码:
app.directive('appendCategory', function(){
return {
restrict: 'E',
controller: function($scope, $http, $compile, $filter){
$scope.addedCategories = [];
$scope.categoryList = "";
$http.get('/api/categories/all-categories').success(function(response){
$scope.categories = response.map(function(category){
return {
name: category.name
}
})
})
$scope.onSelect = function ($item) {
$scope.nameObject = [$item.name];
$scope.addedCategories.push($scope.nameObject);
};
$scope.addCategory = function(){
var myElement = angular.element(document.querySelector('#appended'));
$scope.categoryList = ("<span class='label label-default'>" + $scope.selectedCategory + "<i class='fa fa-times' ng-click='removeCategory()'></i></span>");
var compiled = $compile($scope.categoryList)($scope);
myElement.append(compiled);
$scope.addedCategories.push({category: $scope.categoryList && $scope.selectedCategory, deleted:false});
console.log($scope.addedCategories);
$scope.selectedCategory = "";
}
$scope.removeCategory = function(index){
$scope.addedCategories.splice(index,1);
console.log($scope.addedCategories);
}
},
templateUrl: '/category/category.html'
}
})
Mark-Up:附在此处。
<div class="margin-top-1" id="appended"></div>