Search code examples
angularjsdirectiveangular-ngmodel

ngModel value not reflected on view - changed in directive


value set to false initially in controller

   $scope.isChangeUnsaved = false;

value in view

       Changes Status : {{isChangeUnsaved }} // false initially

i m trying to change the value of ngModel in directive. the value is changed but it is not reflected on view. here is my code i m using

       <form ngc-reload ng-model="isChangeUnsaved">

directive

    angular.module("biApp").directive("ngcReload", ["$parse","$log", function ($parse,$log) {
return {
    restrict: "A",
    scope: {
        ngModel:"="
    },
    link: function(scope, element, attrs, controller){
        $JQ(".mainmenu a").click(function(e){
            e.preventDefault();
             scope.$apply(function() {
                    scope.ngModel = !scope.ngModel;
                });     
             console.log("scope.ngModel",scope.ngModel); // Outputs true - value is changed
        });
    }
}
}]);

value not changed

                Changes Status : {{isChangeUnsaved }} // false even after changed in directive

Solution

  • Try this

            angular.module("biApp").directive("ngcReload", ["$parse","$log", function ($parse,$log) {
     return {
         restrict: 'A',
         require: 'ngModel',
         link: function(scope, iElement, iAttrs, ngModel) {
            $JQ(".mainmenu a").click(function(e){
             e.preventDefault();
             ngModel.$setViewValue(true);
             ngModel.$render();
            });
         }
     }
    

    }]);