【问题标题】:Angular directive didn't update model viewAngular 指令没有更新模型视图
【发布时间】:2016-08-13 19:17:01
【问题描述】:

我试图在使用指令单击表单中的按钮后在模板中显示 cmets

HTML:

<h2>Comments</h2>
<ul class="comments_list">
    <li ng-repeat="com in comments" ng-cloak>{{com.name}} wrote<div class="message">{{com.text}}</div></li>
</ul>
<div class="add_comment" ng-show="posts.length > 0">
    <input type="text" class="form-control" ng-model="addComm.name" placeholder="Your name">
    <textarea class="form-control" ng-model="addComm.text" placeholder="Enter message"></textarea>
    <button class="btn btn-success" add-comment ng-model="addComm">Add</button>
</div>

还有 JS:

app.directive('addComment', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function ($scope, element, attrs, ngModel) {
            element.on("click", function(event){
                event.preventDefault();
                console.log(ngModel.$modelValue);
                $scope.comments.push(angular.copy(ngModel.$modelValue));
            });
        }
    }
});

但在 HTML 中单击“添加”后,我的视图没有更新。如果我刷新页面(我正在使用 ngStorage) - 新评论将出现在列表中,但在单击“添加”按钮后不会出现。

【问题讨论】:

    标签: javascript angularjs model-view-controller angularjs-directive angularjs-scope


    【解决方案1】:

    当你在异步回调中改变模型时,你应该把它封装成$apply:

    $scope.$apply(function(){
        $scope.variable = true;
    });
    

    另一种解决方案是直接调用$apply,更改后:

    $scope.variable = true;
    $scope.$apply();
    

    【讨论】:

      【解决方案2】:

      您不需要 ngModelCtrl,因为该值已附加到范围。

      但是导致问题的原因是您没有通知 Angular 模型已更改,为此,只需调用 $scope.$apply

      【讨论】:

        【解决方案3】:

        发生这种情况是因为您在 javascript click 处理程序中更改了 $scope 变量的值。试试这个:

        app.directive('addComment', function() {
            return {
                restrict: 'A',
                require: 'ngModel',
                priority: 1,
                link: function ($scope, element, attrs, ngModel) {
                    element.on("click", function(event){
                        event.preventDefault();
                        console.log(ngModel.$modelValue);
                        $scope.$apply(function() {
                             $scope.comments.push(angular.copy(ngModel.$modelValue));
                       });
                    });
                }
            }
        });
        

        【讨论】:

          【解决方案4】:

          您应该通知 Angular 发生了一些变化:

          element.on("click", function(event){
              event.preventDefault();
              console.log(ngModel.$modelValue);
              $scope.$apply(function () {
                  $scope.comments.push(angular.copy(ngModel.$modelValue));
              });
          });
          

          【讨论】:

            猜你喜欢
            • 2020-03-03
            • 2014-07-22
            • 1970-01-01
            • 2016-11-30
            • 1970-01-01
            • 1970-01-01
            • 2018-11-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多