Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive didn't update model view

I'm trying to show comments in template after clicking button in form using directive

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>

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

But after clicking "Add" in HTML my view didn't update. If I refresh the page (I'm using ngStorage) - new comment will appear in list, but not after clicking "Add" button.

like image 238
Demyd Ganenko Avatar asked Dec 10 '22 17:12

Demyd Ganenko


1 Answers

It's happening because you are changing the value of your $scope variable inside javascript click handler. Try this:

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));
               });
            });
        }
    }
});
like image 159
Pratik Bhattacharya Avatar answered Dec 21 '22 15:12

Pratik Bhattacharya