Angular 6 custom directive with ng-model
Asked Answered
W

1

-4

This is the directive i have created using Angular 6

myProSupMod.directive('dfct', ['$compile', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            ngModel: '='
        },
        template: "<div class='divRow'><div class='divCell label-column'> 
</div><div class='divCell'><input ng-model='ngModel' /></div></div>",            
        replace: true,
        require: 'ngModel',
        link: function ($scope, elem, attr, ctrl) {                
            $compile(elem)($scope.$parent);
        }
    }
}])

And i'm calling the directive from html like

<dfct ng-model="RootObjectName"></dfct>

Html is rendered as expected but the RootObjectName model in the scope is never updated when value of the text field is changed.

please help Thanks

Wollongong answered 22/8, 2018 at 11:41 Comment(1)
@MichaelCzechowski Comments are supposed to be constructive. Please read the Code of Conduct and Expected Behavior to see the examples of how to point users to alternate solutions without being harsh. Cheers.Biisk
W
0

After spending almost 3 days i'm finally able solve this ,here is what i've done just in case if it helpful for somebody

Here is the directive

myProSupMod.directive('dfct', ['$compile', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            model: '=ngModel',
            type: '@type',
            text:'@text'
        },
        template: "<div class='divRow'><div class='divCell label-column'>{{text}} 
        </div><div class='divCell'><input type='{{type}}' data-ng-model='model' /> 
        </div> 
        </div>",
        replace: true,
        require: '^ngModel',
        link: function ($scope, elem, attr, ctrl) {
            $compile(elem)($scope.$parent);
        }
    }
}])

Here is the html i needed directives

<div class="divRow" ng-repeat="c in Data.Controls">
                <dfct ng-model='RootObject[""+c.ModelName+""]' type=" 
{{c.HTMLControlType}}" text="{{c.LabelText}}"></dfct>
        </div>

If there is a better way please do let me know

Wollongong answered 24/8, 2018 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.