ng-if不适用于ng-change

时间:2016-10-26 08:21:45

标签: javascript angularjs

我正在使用AngularJS并尝试使用$ scope.status使微调器可见且不可见。我在ng-change功能中设置了状态值。它适用于第一行代码,但是当它变得不可见时,$ scope.status已更新,但HTML并没有隐藏微调器。

控制器

angular.module('starter')
  .controller('controller',['$scope','myService',myCtrl]);

function myCtrl($scope,myService){
   var newFunc = function(callback){
       myService.update(function(result){
          console.log("Calling service..."); /* Is calling each time I reload the page */
          result == true ? callback(true) : callback(false);
       });
   };

   $scope.onChangeCode = function(){
      console.log("onChanging...");
      $scope.status = true;
      newFunc(function(result){
         $scope.status = false; /* Status set to false, BUT HTML didn't update, spinner still showing*/
      });
   }
}

HTML

<span ng-if="status == true">
    <ion-spinner  icon="spiral"></ion-spinner>
</span>
<input ng-model="code" ng-change="onChangeCode()"/>

问题

  

ng-if = true适用于使微调器可见,但在ng-change中ng-if = false时它没有隐藏微调器。

5 个答案:

答案 0 :(得分:0)

  

在您的代码中缺少ngModel,ngChange需要绑定ngModel,因为需要ngModel

&#13;
&#13;
var app = angular.module("app", []);

app.controller("ctrl", function($scope){
$scope.checkIt = function() {
  console.log("here")
}
})
&#13;
<body ng-app="app" ng-controller="ctrl">
  
  <input ng-model="me" ng-change="checkIt()">
  
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

根据您向我们展示的代码,我不认为每次刷新它都会调用myService.update。可能您可能需要添加myService的样子

你真的需要newFunc吗?那部分令人困惑 我想你可能会做类似

的事情
$scope.onChangeCode = function(){
    console.log("onChanging...");
    $scope.status = true;
    myService.update(function(result){
        $scope.status = result
    });
}

答案 2 :(得分:0)

更改值后,由于我认为回调,视图没有更新。更新状态后使用$scope.$apply();;

https://embed.plnkr.co/t191Ed4bAcgbqkkTIIZV/

我希望这有帮助。

答案 3 :(得分:0)

您可以使用ng-show代替ng-ifng-if指令根据表达式删除或重新创建DOM树的一部分。 ng-show指令根据提供给ng-show属性的表达式显示或隐藏给定的HTML元素。而且你可以使用ng-show="status"无论如何都可以使用它。

答案 4 :(得分:0)

我添加了$ scope.status = false;在控制器的顶部。 和$ scope。$ apply();更新后的状态;

也许这项工作

angular.module('starter')
  .controller('controller',['$scope','myService',myCtrl]);

function myCtrl($scope,myService){
     $scope.status = false;//Added this line
   var newFunc = function(callback){
       myService.update(function(result){
          console.log("Calling service..."); /* Is calling each time I reload the page */
          result == true ? callback(true) : callback(false);
       });
   };

   $scope.onChangeCode = function(){
      console.log("onChanging...");
      $scope.status = true;
      newFunc(function(result){
         $scope.status = false; 
      $scope.$apply(); //Added this line
      });
   }
}
相关问题