无法获取指令模板中ng模型中的变量

Cannot get the variable in ng-model in directive template

本文关键字:ng 模型 变量 获取 取指令      更新时间:2023-09-26

我有一个注释输入指令,如下所示,我想在用户发布注释后重置表单。然而,在link函数中,我不能得到ng模型的newComment值。如何解决这样的问题。

注释.html

<div class="directive__commenting">
  <div class="col-content">
    <h4>{{title}}({{count}})</h4>
    <form class="form" name="commentForm" ng-submit="createComment(commentForm, newComment)" ng-if="isLoggedIn()">
      <div class="form-group">
        <textarea class="form-control" name="newComment" rows="3" placeholder="你怎么看?" ng-model="newComment" required></textarea>
      </div>
      <div class="right">
        <span id="count-words" ng-class="{'red': isWordsExceeded(newComment)}">{{140 - newComment.length}}</span>
        <button class="send-button btn btn-default" type="submit" ng-disabled="isWordsExceeded()">{{btnActionTitle}}</button>
      </div>
    </form>
  </div>
</div> <!-- #create-comment -->

注释.指令.js

'use strict';
angular.module('myapp')
  .directive('commenting', function (Auth) {
    return {
      templateUrl: 'components/directive/commenting/commenting.html',
      restrict: 'EA',
      scope: {
        title: '=',
        count: '=',
        btnActionTitle: '=',
        action: '='
      },
      link: function (scope) { //, element, attrs
        scope.isLoggedIn = Auth.isLoggedIn;
        scope.isWordsExceeded = function (newComment) {
          return newComment && newComment.length > 140;
        }; //- isWordsExceeded
        scope.createComment = function (form, newComment) {
          scope.action(form, newComment)
          .then(function () { //success
            // clear the form, however here scope.newComment is undefined
          })
          .catch(function () { //fail 
          });
        };
      }
    };
  });

该指令被添加到一个html文件中,如下所示。

<div class="row" id="create-comment">
  <commenting title="'Comments'" count="model.comments.length" btn-action-title="'Submit comment'" action="createComment"></commenting>
</div> <!-- #create-comment -->

尝试像一样通过scope访问

scope.newComment