kreek
kreek

Reputation: 8834

AngularJS: Update model passed to directive

I'm trying to make a directive that inserts elements after an input (which is tagged with the directive) but also updates the input from the inserted elements.

angular.module('afterDir', [])
.directive('after', function ($compile) {

    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.clickHandler = function (index) {

                console.log(index);
                ngModel.$setViewValue("something");

            }

            var content = angular.element('<ul><li ng-click="clickHandler()">after</li><li ng-click="clickHandler()">after too</li></ul>');
            content.insertAfter(element);
            $compile(content)(scope);

        }
    }
});

The click handler fires but the model does not update, is there something else I need to call to update the model? Thanks!

Upvotes: 1

Views: 2615

Answers (1)

Adam
Adam

Reputation: 1143

If you add an ngModel.$render() after your $setViewValue() you should get what you need.

Here's a plunkr. http://plnkr.co/edit/nZgMiZZD4Vna6vMb4LZr

For some explanation, $setViewValue will update the controllers internal viewValue, it will dirty the form if needed, and it will update the internal modelValue as well as the model itself.

$render will actually take that internal viewValue and push it to the DOM.

Upvotes: 2

Related Questions