简体   繁体   中英

How to explicitly set a text box in a form to dirty?

I already saw questions like, How to set a particular field in a form to dirty in angularjs 1.3 and Angular.js programmatically setting a form field to dirty but they are not working.

I am auto-filling a text box in angularjs as:

$scope.address.city = "Santa Clara";

$scope.address.city.$dirty = true;

And in the html I have ng-model="address.city" ng-model-options="{ updateOn: 'change blur' }" .

However, $scope.address.city.$dirty = true; is giving undefined in the console.

I have used

$http.get("somewebsite.com").success(function(data){ $timeout(function () { $scope.address.city.$dirty = true; }, 0); console.log('$scope.address.city.$dirty',$scope.address.city.$dirty);})

but still I am getting error as TypeError: Cannot set property '$dirty' of undefined

I am using angular 1.3.1 .

In Html,

<form name="formName">
    <input type="text" name="city" ng-model="address.city" 
    ng-model-options="{ updateOn: 'change blur' }" />
</form>

In controller,

$timeout(function () {
    $scope.formName.city.$dirty = true;
}, 0);

note that name attributes are used not the model names.

here is the DEMO

You must have missed name attribute on either form or field . You form name should be address & field name should be city then only you can access $scope.address.city.$dirty in controller scope or UI

Markup

<form name="address">
    <input type="text" name="city" ng-model="address.city" 
    ng-model-options="{ updateOn: 'change blur' }" />
</form>

It could use on html as address.city.$dirty & inside controller it would be $scope.address.city.$dirty

Update

In your case form name address scope is conflicting with your address , you are overriding the address scope variable which already contains form object. So after overriding it all the form property gets erased. See my plunkr in which I reproduced your issue exactly what I'm doing there.

Plunkr with Issue

<form name="form">
    <input type="text" name="city" ng-model="address.city" 
    ng-model-options="{ updateOn: 'change blur' }" />
</form>

Controller

$timeout(function () {
    $scope.form.city.$dirty = true;
}, 0);

Fixed plunkr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM