andrzej andrzej - 2 months ago 17
AngularJS Question

Angularjs ng-click clear input and update scope

1. Directive:

app.directive('inputField', function() {
return {
restrict: 'E',
require: 'ngModel',
scope: {
words: '=ngModel'
},
transclude: true,

template: "<input type='text' ng-model='words' placeholder='Translate' />"
};
});


2. ng-click function:

$scope.clear = function() {
$scope.words = { word: '' };
};


3. View looks like this:

<input-field id='inputWord' value='' name="data1" ng-model="words.word"></input-field>


After click clear()

{{words.word}}

and value in input still exist and $scope is broken.

Please tell me how I can clear all inputs
ng-repeat
and update scope?

SSH SSH
Answer

Try like this.

var app = angular.module('app',[])
app.controller('ctrl',function($scope){
  
  $scope.words = [ {word : 'input1'}, {word : 'input2'}, {word : 'input3'}];
  $scope.clear = function() {
          $scope.words =[ {word : ''}, {word : ''}, {word : ''}];
        };
});
app.directive('inputField', function() {
        return {
            restrict: 'E',
            require: 'ngModel',
            scope: {
                words: '=ngModel'
            },
            transclude: true,

            template: "<input type='text' ng-model='words' placeholder='Translate' />"
        };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="word in words">
  <input-field id='inputWord'  name="data1" ng-model="word.word"></input-field>
    </div>
  <button ng-click="clear()">Clear</button>
</div>