Angularjs ng-单击清除输入和更新范围

时间:2016-09-18 06:40:16

标签: javascript angularjs scope directive

1。指令:

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功能:

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

第3。视图如下所示:

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

点击清除()

{{words.word}}

后,输入值仍然存在且$ scope已损坏。

请告诉我如何清除所有输入ng-repeat并更新范围?

1 个答案:

答案 0 :(得分:1)

试试这样。

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>