AngularJS: Set the model to be = {} again doesn

2019-02-08 14:43发布

问题:

I have a fiddler setup, when i click a reset button it should clear out the input controls, this seems to work but not when the input type='url'

Here is the fiddler

Is there an issue or something that I am not understanding.

When I set

$scope.myform = {};

This seems to clear out the other input type but the input type='url' isn't being cleared.

Anyone know why?

回答1:

The issue you see happens when you don't have a valid value inside the input[type="url"]. An invalid value just stays in the view (the input field) and doesn't get pushed to the scope variable inside ng-model. The variable will be updated only when and if the value is correct.

You can test it by entering a valid value. The reset button will work. If you enter an invalid value it won't.

You can fix it by setting $scope.myform = null instead of $scope.myform = {}. This will empty the field because the scope variable (expression) will be undefined. It will be automatically created by Angular once you enter a valid value inside any of the fields.



回答2:

Because you need to put a valid url in the 2nd box like http://www.abc.com, then the reset button will work.



回答3:

In order to correctly update the view/model, I would suggest that you explicitly reset the model's properties like so:

$scope.reset = function() {
    $scope.myform = {
        foo: '',
        bar: ''
    };
    $scope.formName.$setPristine();
};

Setting 'myform' to an empty object deletes its fields, it doesn't set them to a blank string. It's quite likely angular's cleanup may not be deleting the value the view is referencing, thus the confusion between the application's model and view states.

Hope it helped.