2017-01-27 44 views
1

我試圖編輯一個字段,並在點擊按鈕時將標籤轉換爲文本字段並將其更改回按鍵事件(ng-keypress)上的標籤。使用控制器ng-show ng-hide

我正在通過控制器更改ng-show變量,但它不起作用。

HTML:

<div ng-app> 
    <div ng-controller="showCrtl"> 
     <form> 
     <label ng-hide="editMode" >{{field}}</label> 
      <input ng-show="editMode" ng-keypress="changemode($event) " ng-model="field" > 
      <span class="pull-right" > 
      <button ng-click="editMode=true" class="btn-lg btn-warning" >edit </button>          </span>      
     </form> 

    </div> 
</div> 

JS:

function showCrtl($scope){ 
    $scope.field="Chanel"; 
    $scope.changemode=function(event){ 
    if(event.charCode==13){ 
      $scope.editMode = false; 
    } 
    } 
} 

我的更新JS-小提琴鏈接:http://jsfiddle.net/8Yz7S/281/

回答

3

使用NG模糊的而不是NG-按鍵,

<input ng-show="editMode" ng-blur="changemode() " > 

DEMO

編輯:

使用下面的指令來處理輸入按鍵事件,

app.directive('ngEnter', function() { 
    return function(scope, element, attrs) { 
    element.bind("keydown keypress", function(event) { 
     if (event.which === 13) { 
     scope.$apply(function() { 
      scope.$eval(attrs.ngEnter); 
     }); 

     event.preventDefault(); 
     } 
    }); 
    }; 
}); 

DEMO

+0

然後,只要我開始輸入,它就會標記。 – Rachel

+0

嘗試ng-blur – Sajeetharan

+0

我想編輯字段,然後wehn我按回車它應該改回標籤 – Rachel

0

你想從視圖中模糊的邏輯是可能的。所以,他建議,使用

<input ng-show="editMode" ng-keypress="changemode($event)"> 

然後,做你的邏輯changemode()函數中:

$scope.changemode = function(evt) { 
    $timeout(function() {$scope.editMode = false;},100); 
} 

http://jsfiddle.net/8Yz7S/293/

+0

嗨喬希,我試過了:http://jsfiddle.net/8Yz7S/279/它不工作 – Rachel

+0

您可能需要使用超時強制摘要循環:http://jsfiddle.net/8Yz7S/293/ – Josh

1

你可以嘗試以下解決方案。

<input ng-show="editMode" ng-keypress="changemode($event) " > 

添加間隔更新視圖

function showCrtl($scope, $timeout){ 

    $scope.changemode=function(event){ 
    if(event.charCode==13){ 

    $timeout(function() { 
    $scope.editMode = false; 
    }, 500); 
    } 
    } 
    } 

http://jsfiddle.net/gsjsfiddle/hcu5mkhm/3/

+0

它超時並更改爲標籤,但該字段未更新。 – Rachel

+1

點擊輸入按鈕後,視圖更新爲頻道和編輯按鈕。但我沒有明確地解決你的問題?您期望更新哪個字段? – GrabNewTech

+0

我更新了我的小提琴,使其更加清晰:http://jsfiddle.net/8Yz7S/281/ – Rachel

1

它不是爲你工作的原因是,你是不是防止Enter鍵的默認行爲。所以changemode功能執行後,editmode設置爲false,編輯按鈕的點擊事件也正在執行,設置editmode回到true

所有你需要做的就是調用event.preventDefault();如下圖所示:

function showCrtl($scope){ 
    $scope.field="Chanel"; 
    $scope.changemode=function(event){ 
    if(event.charCode==13){ 
     $scope.editMode = false; 
     event.preventDefault(); // <<<<<<< 
    } 
    } 
} 

要驗證此問題,您可以檢查此琴:http://jsfiddle.net/vnathalye/8Yz7S/301/

試試註釋行event.preventDefault();後,檢查控制檯。

+0

謝謝你解釋 – Rachel