2015-10-12 52 views
-1

我有一些ng模型和輸入元素的問題。請看看這個運動員:http://plnkr.co/edit/PJCv1AsPns1cxuSPTZiU角度trimed輸入值

我的觀點是當我編輯輸入值,並在開始和結束f.e.添加一些空格。

some text  

,並單擊save白空間被修剪(和它的OK)從inputValue,但如果我修改一遍「上一個」空格出現在輸入。如何預防它?我試圖這樣做

angular.element($('#trimInput')).val($scope.inputValue); 

它的工作原理,但我不喜歡這個解決方案。

angular.module('app', []) 
 
    .controller('trim', ['$scope', function($scope) { 
 
    
 
    $scope.inputValue = "some text"; 
 
    $scope.editMode = false; 
 
    
 
    $scope.edit = function() { 
 
     $scope.editMode = true; 
 
    }; 
 
    
 
    $scope.save = function() { 
 
     $scope.editMode = false; 
 
     //angular.element($('#trimInput')).val($scope.inputValue); 
 
     console.log($scope.inputValue); 
 
     console.log($scope.inputValue.length); 
 
    }; 
 
    
 
    }])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<body ng-app="app"> 
 
    <div ng-controller="trim"> 
 
    <div ng-show="!editMode"> 
 
     [{{inputValue}}] 
 
     <button ng-click="edit()">edit</button> 
 
    </div> 
 
    <div ng-show="editMode"> 
 
     <input id="trimInput" type="text" ng-model="inputValue" /> 
 
     <button ng-click="save()">save</button> 
 
    </div> 
 
    </div> 
 
</body>

+0

downvoted因爲你通過添加plunkr鏈接,無碼 – sirrocco

+0

避免規則修正模型值,而不是DOM元素值 – charlietfl

+0

但模型沒有空格,它們只出現在輸入元素中 – user3452568

回答

0

默認ng-trimtrue在角所以它會自動範圍調整值。但價值不會更新input,意味着額外的輸入將在那裏。您必須手動分配它。

$document[0].getElementById("trimInput").value = $scope.inputValue; 

爲此,您需要在應用程序中注入$document。保存時會自動將修剪值分配給輸入。

See DEMO