ngModel值未反映在视图中 - 在指令中更改

时间:2015-07-28 11:22:11

标签: angularjs directive angular-ngmodel

值最初在控制器中设置为false

   $scope.isChangeUnsaved = false;

视图中的值

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

我试图在指令中更改ngModel的值。值已更改但未在视图中反映。这是我使用的代码

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

指令

    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
        });
    }
}
}]);

值未更改

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

1 个答案:

答案 0 :(得分:1)

试试这个

        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();
        });
     }
 }

}]);