对表单输入没有保存价值模型输入指令AngularJS [英] AngularJS on enter directive on form input no saving Model value

查看:130
本文介绍了对表单输入没有保存价值模型输入指令AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在某网页上的 - 满code在这个 Plunker

I have the following on a page - full code in this Plunker

有一个自定义调用时输入一个函数的OnEnter 指令pssed上聊天表单输入$ P $。 code段以下

There is a custom onEnter directive that calls a function when enter is pressed on a chat form input. Code snippet below

//**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;
  };
});

问题是输入的值(的消息)不被保存到范围模型(聊天)。如果我删除它的工作原理的OnEnter 指令。我缺少的是在这里吗?任何帮助将是巨大的。

Problem is the value of the input (message) is not saved into the scope model (chat). If I remove the onenter directive it works. What am I missing here? Any help will be great

推荐答案

好了它。原来,当你定义在你的指令,创建一个新的子范围的范围对象。发现这里的细节:

Ok figured it out. Turns out when you define a scope object in your directive you create a new child scope. Details found here:

<一个href=\"http://stackoverflow.com/questions/16145571/directive-with-scope-breaking-ngmodel-of-an-input?answertab=active#tab-top\">Directive与范围打破ngmodel输入的

要解决这个问题我删除了范围声明,并从 ATTRS 对象使用的函数的值。

To fix this I removed the scope declaration and used the value of the function from attrs object.

指令现在看起来是这样的:

Directive looks like this now:

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

这篇关于对表单输入没有保存价值模型输入指令AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆