如何在数据更改时更新AngularJS中的视图

时间:2015-03-03 17:21:24

标签: javascript angularjs ruby-on-rails-4

我似乎无法做到这一点:我有一个包含类别(对象)和帖子对象的数组:

var categories = $http.get('/api/categories').success(function (data) {
    $scope.categories = data;
});

// The code below uses a Rails gem to transport data between the JS and Rails. 
$scope.post = gon.post;

// Suffice to say the $scope.post is an object like so:
...
_id: Object { $oid="54f4706f6364653c7cb60000"}
_slugs: ["first-post"]
author_id: Object { $oid="54ef30d063646514c1000000"}
category_ids: [Object, Object]
...

正如您所看到的,post对象有一个属性category_ids,这是一个数组,其中包含与此帖相关的所有类别。在我看来(haml)我有以下内容:

%label 
    %input{"type" => "checkbox", "ng-model" => "cat.add", "ng-change" => "addCategory(cat)", "ng-checked" => "currentCat(cat)"} {{cat.name}}

如您所见,ng-checked会触发currentCat()函数:

$scope.currentCat = function (cat) {
    for (var i = 0; i < cat.post_ids.length; i++){
        if (cat.post_ids[i].$oid == $scope.post._id.$oid) {
            return true;
        }
    }
};

上面的函数循环遍历post中的类别(post对象的category_ids属性),并将其与给定的参数进行比较。它适用于现有类别。当我动态添加新类别并将其推送到类别数组中时,会出现问题:

$scope.addCatBtn = function () {
    var category = $scope.cat;
    $http.post('/api/categories', category).success(function (data) {
        $scope.categories.push(data.category);
        $scope.cat = '';
        $scope.addCategory(data.category);
    });
};

新类别未显示&#39;已检查&#39;在视图中。我错过了什么? 任何想法都将不胜感激。

编辑:添加addCategory函数:

$scope.addCategory = function (cat) {
    var found = false;
    for (var i in $scope.post.category_ids) {
        if (cat._id.$oid === $scope.post.category_ids[i].$oid) {
            $scope.post.category_ids.splice(i, 1);   // splice, not slice
            found = true;
        }
    }
    if (!found) {  // add only if it wasn't found
        $scope.post.category_ids.push(cat._id);
    }
    console.log($scope.post);
}

1 个答案:

答案 0 :(得分:0)

ngModelngChecked并不意味着一起使用。

您可以使用ngModel