AngularJS ng-show(不随布尔值改变)

时间:2015-04-13 03:16:28

标签: javascript angularjs angularjs-ng-show

我已经显示了我正在显示的项目列表,并希望用户从列表中删除任何项目(通过复选框和删除按钮)。当我选择项目并从按钮调用一个函数时,我可以访问这些项目(更改它们的文本和诸如此类的东西),但是设置它们相应的布尔绑定到ng-show为false似乎不起作用。有人建议尝试$ scope。$ apply()但是这给了我错误 - 互联网说它的b / c Angular正处于摘要的中间。 Anywho,是一个简单的版本。

angular.module('myApp', ['ngSanitize'])
.controller("itemController", ['$scope','$location',function($scope,$location) {

$scope.items = [];
$scope.to_hide = [];

for ( var i = 0; i < 10; i++) {
    var id = i;
    var title = "Some Title";
    var is_visible = true;

    var item = { "id" : id,
                 "title" : title,
                 "visible" : is_visible }

    $scope.items.push_back(item);
}

$scope.toggleSelection = function(item) {
    $scope.to_hide.push(item.id);   
}

$scope.handleDelete = function(item) {
    for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.to_hide.indexOf($scope.items[i].id) > -1) {
            # Can directly edit item here -- but visibility stays the same 
            $scope.items[i].visible = false;
        }
    }

    $scope.$apply(); // This gives errors.
};

})];

HTML

<div ng-app="myApp" ng-controller="itemController">
    <div ng-repeat="item in items" ng-show="{{item.visible}}>
        <input type="checkbox" ng-click="toggleSelection(item)">
    </div>
    <div>
        <div>{{item.title}}</div>
    </div>
</div>

1 个答案:

答案 0 :(得分:3)

你不需要像ng-show和ng-hide这样的属性进行插值。而且,我猜测而不是发送项目本身,你应该只是发送项目索引并相应地在控制器中访问它。 / p>

所以这是你可以做到的。将您的HTML更新为:

    <div ng-app="myApp" ng-controller="itemController">
        <div ng-repeat="item in items" ng-show="item.visible>               <input type="checkbox" ng-click="toggleSelection($index)">
        </div>
        <div>
            <div>{{item.title}}</div>
        </div>
    </div>

然后在JS:

    $scope.handleDelete = function(item) {
        $scope.items[$index].visible = false;
    };
相关问题