4

我試圖用點擊按鈕的形式指令角指令沒有更新

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) - 新評論將出現在列表中,但不會在點擊「添加」按鈕後出現。

回答

5

它的發生,因爲你正在改變JavaScript的點擊處理程序中的$範圍變量的值。試試這個:

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)); 
       }); 
      }); 
     } 
    } 
}); 
3

您應通知角事情有了變化:

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

您不需要ngModelCtrl,因爲該值已附加到範圍。

但是什麼導致的問題是,你不通知的角度,該模型的變化,爲了做到這一點,只需調用$範圍。$應用

1

當您在異步回調改變模式,你應該將其封裝成$apply

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

的替代解決方案是直接調用$apply,變更後:

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