【问题标题】:How to update the view in AngularJS when the data changes数据更改时如何更新AngularJS中的视图
【发布时间】:2015-03-03 17:21:24
【问题描述】:

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

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]
...

如您所见,帖子对象有一个属性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;
        }
    }
};

上面的函数循环遍历帖子中的类别(帖子对象的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);
    });
};

新类别未在视图中显示为“已选中”。我错过了什么? 任何想法将不胜感激。

编辑:添加 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);
}

【问题讨论】:

  • addCategory 函数是什么样的?
  • 您是否测试过在通话后接收数据? $http.post('/api/categories', category).success(function (data) { console.log(data.category); // 或者类似的东西
  • 我添加了addCategory函数
  • 是的,data.category 很好,看起来像其他类别,因此我的结论是,问题可能是在将新类别添加到数组时 currentCat 函数没有触发跨度>

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


【解决方案1】:

ngModelngChecked 不能一起使用。

使用ngModel 应该没问题。

【讨论】:

  • 在这种情况下如何分配检查状态?
  • 将代表该字段的模型值设置为true。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 2019-05-05
相关资源
最近更新 更多