简体   繁体   中英

Value of ng-model undefined in custom directive

I am writing a custom directive which calls a legacy javascript date control we are using in other places.. The issue I am facing is the value of the ng-model I send in is always undefined.

This value is coming from a $http.get which is executed in the controller. The code for the directive seems to be hit before the controller code is run which is why this is happening. Is there a way for me to tell the directive only to run after the controller has been initialized?

app.directive('dateControl', function () {
    return {
        restrict: 'A',
        require: '^ngModel',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attr) {
            // scope.ngModel is undefined in here
            alert(scope.ngModel);
            addCalControlAngular(attr.id, scope.ngModel, attr.ngModel, attr.id);
        }
    }
});


<td date-Control ng-model="postAward.letterOfAwardDespatchDate" id="letterofaward">

The directive is not 'hit' before controller if it's inside controller, but if the value comes from http request then it's undefined until the model is updated with value (hope that makes sense), to assure that directive is executed after receiving data from http you can do a small trick with ng-if

<td procon-Date-Control ng-if="postAward.letterOfAwardDespatchDate" ng-model="postAward.letterOfAwardDespatchDate" id="letterofaward">

If you do it that way directive is going to be rendered in view only of the ng-if is not null/undefined or the expression is truthy ie ng-if="postAward.letterOfAwardDespatchDate == 'yesterday'"

I resolved this with a $watch in my link function

link: function (scope, element, attr) {
            debugger;
            // Watch for a value in ngModel and render that value, otherwise give a default
            scope.$watch('ngModel', function (newVal) {
                if (newVal) {
                    addCalControlAngular(attr.id, scope.ngModel, attr.isMandatory, attr.showDefault, attr.ngModel, attr.id);
                } else {
                    addCalControlAngular(attr.id, c_NULL_DATE, attr.isMandatory, attr.showDefault, attr.ngModel, attr.id);
                }
            })            
        }

If you want to use ngModel try to add a argument in link function to add a injection like this:

link: function (scope, element, attr, ngModel)

After this, you can use code like ngModel.$render and so on, hope that helpful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM