2013-08-22 42 views
5

頁面上,我有以下 - 在這個PlunkerAngularJS對錶單輸入輸入指令,沒有儲蓄模型值

完整的代碼有一個自定義onEnter指令壓在聊天的形式輸入時輸入調用一個函數。代碼段下面

//**HTML View** 
<div ng-controller="mainCtrl"> 
    <ul> 
     <li ng-repeat="chat in chatMessages"> 
     {{chat.username}}<br/> 
      {{chat.message}} 
     </li> 
    </ul> 
</div> 
<form id="chatForm" name="chatForm" ng-controller="formCtrl"> 
    <label for="chat-username">User: </label> 
    <input type="text" id="chat-username" class="chat__username" ng-model="chat.username" required> 
    <label for="chat-input">Chat: </label> 
    <input type="text" id="chat-input" class="chat__input" on-enter="sendChat()" ng-model="chat.message" required> 
    <a href="#" class="chat__submit icon-comments" id="chat-submit" ng-click="sendChat()" ng-disabled="isChatValid()">Chatme</a> 
</form> 


//**Javascript** 
app.controller('formCtrl',function($scope,Chats){ 
    $scope.sendChat = function() { 
    if($scope.isChatValid()) { 
     return; 
    } 
    console.log(JSON.stringify($scope.chat)); 
    var msg = {}; 
    angular.copy($scope.chat,msg); 
    Chats.data.push(msg);  
    }; 

    $scope.isChatValid = function() { 
    return $scope.chatForm.$invalid; 
    }; 
}); 

問題是輸入(message)的值不被保存到鏡體模型(chat)。如果我刪除onenter指令它的作品。我在這裏錯過了什麼?任何幫助將是偉大的

回答

12

好吧,算了一下。當你在你的指令中定義一個範圍對象時,你會創建一個新的子範圍。詳情在這裏找到:

Directive with scope breaking ngmodel of an input

爲了解決這個問題,我刪除了scope聲明,並從attrs對象使用的函數的值。

指令現在看起來是這樣的:

app.directive('onEnter',function() { 

    var linkFn = function(scope,element,attrs) { 
    element.bind("keypress", function(event) { 
     if(event.which === 13) { 
     scope.$apply(function() { 
     scope.$eval(attrs.onEnter); 
     }); 
     event.preventDefault(); 
     } 
    }); 
    }; 

    return { 
    link:linkFn 
    }; 
}); 

全部代碼plunker

+0

啊沒有看到你也得到了它 – shaunhusain

+1

個人我不喜歡這個解決方案,因爲它使用$ eval – Iamisti

+1

在開始時我和@lamisti有同樣的觀點。然而,我意識到這個解決方案有很大的優勢 - 它不會創建隔離範圍,因此與隔離範圍內的其他潛在指令不會發生衝突,這可能會應用於同一個DOM元素。 – Klon

1

您應該使用$parent來指代chat對象這樣

$parent.chat.message 

由於您使用的指令,它聲明一個子範圍。以下是完整的HTML:

<input type="text" id="chat-input" class="chat__input" on-enter="sendChat()" ng-model="$parent.chat.message" required> 
+0

謝謝你的答案@ sza,我想到這是一個範圍的東西,並解決了它 –

3

對角1.2我寫的一樣:

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

app.directive('onEnter', function() { 
    return { 
     scope: {onEnter: '&'}, 
     link: function(scope, element) { 
      console.log(scope); 
      element.bind("keydown keypress", function(event) { 
       if(event.which === 13) { 
        scope.onEnter(); 
        scope.$apply(); 
       } 
      }); 
     } 
    } 
}); 
+0

改進的解決方案將是: 範圍。$ apply(function(){ scope.onEnter(); }); – Iamisti

相關問題