【问题标题】:How to copy/store a scope variable's original value without updating it when the scope variable updates如何在范围变量更新时复制/存储范围变量的原始值而不更新它
【发布时间】:2016-01-20 15:15:29
【问题描述】:

我有一个简单的任务,结果并不是那么简单。我需要复制一个$scope 变量,而不使用angular.copy(),因为如果我使用复制功能,对象就不能如果进行了更改,请与观察者的newVal 进行比较,因为它不是同一个对象。所以if (newVal !== original) 永远不会评估为false。如何存储范围变量的原始值但不再更新此变量,即使范围变量发生更改?有可能吗?

core.directive('saveButton', function () {

    return {
        scope: {
            actionParams: '=',
        },
        templateUrl: 'app/views/components/core/save-button.html',
        link: function(scope, element, attrs) {

            var original = scope.actionParams;

            scope.$watch(function() {
                return scope.actionParams;
            }, function(newVal, oldVal) {

                // I want to check if the original value has changed, not the previous value
                if (newVal !== original) {
                    scope.changed = true;
                }
                else {
                    scope.changed = false;
                }
            }, true);
        }
    }
});

【问题讨论】:

标签: angularjs


【解决方案1】:

只存储 json 表示形式 - 它永远不会改变,您始终可以将其与新值的 json 表示形式进行比较。 https://docs.angularjs.org/api/ng/function/angular.toJson

或者您可以使用 angular.equals 比较对象: angular.equals({b : { c : [1, 2]}, a : 'a'}, {a : 'a', b : { c : [1, 2]}}) >> 是的

【讨论】:

  • 实际上有效,但人是丑陋的.. 但是尝试了 3 小时后,我不在乎了:P 欢呼!
猜你喜欢
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多