Atlas91
Atlas91

Reputation: 5904

Angularjs clear input text field

I have this situation:

http://jsfiddle.net/f8erG/48/

With some input text. When i fill the input i can hide them by a button. What i need is that when the input hides all content inside that was typed clear. So when i click "Show" button the input must be empty. I can't using ngIf before someone ask me.

This is the code:

<div ng-controller="myCtrl">
    <button ng-click="hideStuff()">Hide!</button>
    <button ng-click="showStuff()">Show!</button>
    <div ng-repeat="item in inputFileds">
        <input placeholder="{{item.label}}" class="default" ng-hide="hidden" ng-class="{'fade': startFade, 'show': !startFade}" type="text" ng-model="item.value" />
    </div>
</div>

And javascritp

var myApp = angular.module('myApp', []);

myApp.controller("myCtrl", function($scope, $timeout) {
    $scope.hideStuff = function() {
        $scope.startFade = true;
        $timeout(function() {
            $scope.hidden = true;
        }, 700);

    };

    $scope.showStuff = function() {
        $scope.startFade = false;
        $timeout(function() {
            $scope.hidden = false;
        }, 700);

    };


    $scope.inputFileds = [{
        "label": "input1",
        "value": ""
    }, {
        "label": "input2",
        "value": ""
    }, {
        "label": "input3",
        "value": ""
    }, {
        "label": "input4",
        "value": ""
    }];
});

Upvotes: 4

Views: 25770

Answers (3)

morpheus05
morpheus05

Reputation: 4872

I added

for(var i = 0; i < $scope.inputFileds.length; ++i) {
        $scope.inputFileds[i].value = "";
    }

in your hide function.

Its important to understand, that angular uses double binding in this case. That means, if you update your model inside the controller, it will be reflected back. Thats why you can change the model object and the form will show an empty input field.

Upvotes: 0

Michael
Michael

Reputation: 3104

You can avoid such problems with the right design!

Why do you put configuration data (labels) into the model? Separate them into 2 object, because the labels are static, but the input field values are not. You can then just reset the modal very simple.

$scope.model = {};

That's it - not need to reset every single field!

Upvotes: 5

David
David

Reputation: 825

Try to reinitialize the input fields:-> http://jsfiddle.net/maralik/f8erG/56/

$scope.showStuff = function () {
    $scope.initInputFields();
    $scope.startFade = false;
    $timeout(function(){
        $scope.hidden = false;
    }, 700);

};

$scope.initInputFields = function() {
    $scope.inputFileds = [{
            "label": "input1",
            "value": ""
        },{
            "label": "input2",
            "value": ""
        },{
            "label": "input3",
            "value": ""
        },{
            "label": "input4",
            "value": ""
        }];        
};

$scope.initInputFields();

Upvotes: 0

Related Questions