Search code examples
angularjsangularjs-directiveangularjs-ng-transclude

Transcluded input ng-model does not update scope variable passed to directive


I have a directive that is essentially a complicated label tag that transcludes an input element and takes the input box's ng-model as a parameter.

<div switch model="testObject.switch">
    <input type="checkbox" ng-model="$parent.testObject.switch">
</div>

Prior to upgrading to angular 1.4, clicking on the directive updated the ng-model and triggered the watch inside the directive.

Now, clicking on the directive still affects the input box, but the value inside the directive is unaffected.

I would appreciate any insight into what caused this change and how to fix it.

fiddle


Solution

  • I have updated your fiddle with working code. If you require ngModel in your directive and watch its $modelValue, you are able to get the behavior that you are looking for.

    HTML:

    <div switch ng-model="testObject.switch">
    

    Directive:

     booleanSwitchModule.directive('switch', [function () {
      return {
        scope: {},
        require: "?^ngModel",
        link: function (scope, elem, attr, ngModel) {
            var timesChanged = 0;           
    
            scope.$watch(function() {return ngModel.$modelValue; }, function (val) {
    
                if (val != undefined) {
                    alert("model changed " + ++timesChanged + " times");
    
                    scope.switchPosition = scope.model;
                }
            });
    
    
        },
        restrict: 'EA',
        replace: true,
        transclude: true,
        template: '<label class="switch">' +
            'directive scope model: {{ngModel}}' +
            '<span ng-transclude></span>' +
            '</label>',
      }
    }]);
    

    Here is the updated fiddle: https://jsfiddle.net/62911kx5/3/