angularjs - Angular 输入值未更改。即旧值 == 新值

标签 angularjs angularjs-directive

当输入字段修改时,无论 newValue==oldValue 与否,Angular 都会向输入字段添加“ng-dirty”类。

即如果输入值为“manohar”,我删除“r”并将其添加回来。即使值为“manohar”(原始值),“ng-dirty”类仍然存在。

有没有办法检查输入值是否被修改(newValue != oldValue)?

提前致谢。

最佳答案

如果您想根据表单中数据的实际状态(编辑与原始)来处理行为,您需要自己跟踪。就像 Cétia 所说的那样,dirty/prestine 只是为了跟踪交互和验证,而不是状态。

这可能有点矫枉过正,但我​​通常会这样做:

.controller('MyController', function ($scope, Restangular) {


    /**
     * @ngdoc property
     * @name  _dataWatcher
     * @private
     * @propertyOf MyController
     *
     * @description
     * Holds the watch stop-method, if the "data-has-changed" watcher is active.
     */
    var _dataWatcher;


    /**
     * @ngdoc property
     * @name data
     * @propertyOf MyController
     *
     * @description Stores "original" and "edit" copy of the data beeing handled by the form.
     */
    $scope.data = {};


    /**
     * @ngdoc property
     * @name data
     * @propertyOf MyController
     *
     * @description Stores state for the view.
     */
    $scope.state = {
        loading: true,
        saving: false,
        hasChanged: false,
        hasBeenSaved: false
    };


    /**
     * @ngdoc method
     * @name _setup
     * @private
     * @methodOf MyController
     *
     * @description Run on controller init.
     */
    function _setup() {
        $scope.reset();
        $scope.state.loading = false;
    };


    /**
     * @ngdoc method
     * @name _startWatcher
     * @private
     * @methodOf MyController
     *
     * @description
     * Setup watcher for changes in data.test. Stop method will be saved to
     * private property _dataWatcher.
     */
    function _startWatcher() {
        _dataWatcher = $scope.$watch('data.edit', function (newValue, oldValue) {
            if (newValue !== oldValue) {
                if (JSON.stringify(newValue) === JSON.stringify($scope.data.original)) {
                    $scope.state.hasChanged = false;

                    // If you want the form to act like its untouched if no changes are found:
                    $scope.nameOfYourForm.$setPristine();
                } else {
                    $scope.state.hasChanged = true;
                }
            }
        }, true);
    }


    /**
     * @ngdoc method
     * @name _stopWatcher
     * @private
     * @methodOf MyController
     *
     * @description
     * Stop watching data.test for changes. This is needed for "reset" and
     * syncing data without triggering data-has-changed loop.
     */
    function _stopWatcher() {
        if (!_dataWatcher) {
            return;
        }
        _dataWatcher();
    }


    /**
     * @ngdoc method
     * @name save
     * @methodOf MyController
     *
     * @description
     * Save data.edit changes to database, Restangular is used in example but you get the idea.
     */
    $scope.save = function () {
        var newData;

        // Set states
        $scope.state.error = false;
        $scope.state.saving = true;

        // Update with new data
        // $scope.entity is a restangularized object from some server
        newData = Restangular.copy($scope.entity);
        newData.name = $scope.data.edit.name;
        newData.status = $scope.data.edit.status;

        // Save to db
        newData.put().then(function (entity) {
            _stopWatcher();

            // Db returns saved data, update restangular object, to update 
            // data in view.
            $scope.entity.name = entity.name;
            $scope.entity.status = entity.status;

            $scope.reset();

            $scope.state.hasBeenSaved = true;
        }, function (error) {
            $scope.state.hasChanged = true;
            $scope.state.error = error.data;
        }).finally(function () {
            $scope.state.saving = false;
        });
    };


    /**
     * @ngdoc method
     * @name reset
     * @methodOf MyController
     *
     * @description
     * Resets the data object to current state of the original source
     * object. Any unsaved changes in data.edit will be overwritten.
     */
    $scope.reset = function () {
        // Stop watcher, if initialized
        _stopWatcher();

        // Save original data (for comparison)
        $scope.data.original = {
            status: $scope.feed.status,
            name: $scope.feed.name
        };

        // Create new copy of editable data
        $scope.data.edit = angular.copy($scope.data.original);

        // Make sure state signals "not changed"
        $scope.state.hasChanged = false;

        // Force form to be prestine
        $scope.nameOfYourForm.$setPristine();

        // Start watching changes
        _startWatcher();
    };


    _setup();
});

关于angularjs - Angular 输入值未更改。即旧值 == 新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232799/

相关文章:

html - Angularjs Angular 计时器和 $http

javascript - 执行 ElementArrayFinder

AngularJS + OAuth

javascript - 如何从按钮检查输入单选 - AngularJS

javascript - 将 JSON 对象从 Angular 服务传递给指令

javascript - 如何在 Angularjs 中 dom 完成渲染后运行指令

javascript - 如何在 JavaScript(Google Chart) 中使用 Angular JS 数据?

angularjs - 在嵌套的 Angular 指令中使用 ng-transclude 和 ng-include

javascript - 无法在 Angular 组件中设置绑定(bind)属性的值

javascript - 在 Angular app.routes.js 解析函数中使用参数