AngularJS 检查下载的 json 是否与工作副本不同

AngularJS check if downloaded json has difference between working copy

我下载json所以:

$scope.getarticles = function(company) {
  $http.get("url", {
      headers: {
        'Content-Type': 'application/json',
        'If-Modified-Since': ''
      }
    })
    .success(function(response) {
      $.each(response, function(ind, el) {
        $scope.articles.push(el);
      });
    })
    .error(function(err, status) {
    });
};

并且我使用我的 $scope.articles 并且对于一些对象我可以更改数据(注意,它也可以有排序 uid 等,不要比较它们) - 如何比较我的数据与数据我从 json 得到的?喜欢

     $.each($scope.articles, function(ind, el) {
        if (el == $scope.copyArticles)
          console.log("yes");
      });

这是真的吗?如果是,那么如何?

没有简单的内置方法,尤其是当您必须忽略某些字段时,例如排序 UID。

它只是回到基本 Javascript。

例如,定义一个函数来比较两篇文章是否相等,忽略任何您不关心的字段。为方便起见,我使用 Lodash or UnderscoreJS 中的 _.omit() 函数删除我不关心的键,并使用 angular.equals() 对结果对象进行深入比较。

function articlesAreEqual(article1, article2) {
    return angular.equals(strippedArticle(article1), strippedArticle(article2));
}

function strippedArticle(a) {
    return _.omit(a, 'sortUID' /* add other keys here */);
}

然后您可以查看下载的是否与现有的匹配:

$scope.getarticles = function(company) {
  $http.get("url", {
      headers: {
        'Content-Type': 'application/json',
        'If-Modified-Since': ''
      }
    })
    .success(function(response) {
      $.each(response, function(ind, el) {
        if (articlesAreEqual($scope.articles[ind], el)) {
            console.log('Article #' + (ind + 1) + ' is the same.');
        } else {
            console.log('Article #' + (ind + 1) + ' differs.');
            $scope.articles.splice(ind, 1, el); // replace the existing one
        }
      });
    })
    .error(function(err, status) {
    });
};