Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数据更改时如何在AngularJS中更新视图_Javascript_Angularjs_Ruby On Rails 4 - Fatal编程技术网

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

Javascript 数据更改时如何在AngularJS中更新视图,javascript,angularjs,ruby-on-rails-4,Javascript,Angularjs,Ruby On Rails 4,我似乎无法正确理解这一点:我有一个包含类别对象和post对象的数组: 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; //

我似乎无法正确理解这一点:我有一个包含类别对象和post对象的数组:

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_id,它是一个包含与此post关联的所有类别的数组。在我看来,我有以下几点:

%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;
        }
    }
};
新类别在视图中不显示为“已选中”。我错过了什么? 如有任何想法,将不胜感激

编辑:添加addCategory功能:

$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;
        }
    }
};
ngModel和ngChecked不能一起使用


您可以直接使用ngModel。

addCategory函数是什么样子的?您是否测试过在post调用后接收数据$http.post'/api/categories',category.successfunction数据{console.logdata.category;//或者类似的东西我添加了addCategory函数是的,data.category很好,并且看起来像其他类别,因此我的结论是,当向阵列添加新类别时,可能问题在于currentCat函数没有启动。那么,在这种情况下,如何分配选中状态?请重新设置模型值将该领域呈现为真。
$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);
}