Search code examples
angularjsangularjs-directiveangular-ngmodel

ngModel passed through wrapper to child directive


Let's imagine, we have one child directive <child/>, that takes ng-model and ng-change and does some actions with them. And we have two kind of wrappers <w1/> and <w2/>, that contain <child/>.

  • W1 should pass ng-model through directly to <child/>
  • W2 should pass some inner object as model to <child/>

in first case i would use require: '^ngModel' in second : require: 'ngModel' but i need them to work simultaneously


Solution

  • so model is simple object that can be passed easily through.

    <wrapper ng-model="foo"></wrapper>

    Wrapper:

    module
    .directive('wrapper', function () {
        return {
            restrict: 'E',
            template: "<child ng-model='ngModel'></child>",
            scope: {
                ngModel:'='
            },
            link: function ($scope) {
            }
        };
    });
    

    Child:

    module
        .directive('child', function () {
            return {
                restrict: 'E',
                require: 'ngModel',
                template: "<div>some wierd stuff</div>",
                scope: {
                },
                link: function ($scope, iElem, iAttr, ngModel) {
                    var a = ngModel.$viewValue;
                }
            };
        });