无法在指令模板中获取ng-model中的变量

时间:2015-11-05 09:14:01

标签: javascript angularjs angularjs-directive

我有一个注释输入指令如下,我想在用户发布评论后重置表单。但是,我无法在newComment函数中获得ng-model的link值。如何解决这个问题。

commenting.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 -->

commenting.directive.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 -->

1 个答案:

答案 0 :(得分:0)

尝试通过scope.newComment 访问

step