Angular 6 custom directive with ng-model

好久不见. 提交于 2019-12-13 10:01:49

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/51966080/angular-6-custom-directive-with-ng-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!