Passing AngularJS ng-form object into ng-if?

2019-08-10 02:20发布

问题:

When I click "preview" here the save button in my preview mode is not disabled http://plnkr.co/edit/I3n29LHP2Yotiw8vkW0i

I think this is because the form object (testAddForm) is not available in the scope of the ng-if. I know that I should use an object in my controller because it's passed down all the way, but the form object is created by angular and not available in the ng-if. How can I work around that?

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.2.27" data-semver="1.2.27" src="https://code.angularjs.org/1.2.27/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="TestController">
    <form name="testAddForm" novalidate>
      <div ng-if="!previewMode">
        <input name="title" ng-model="data.title" required />
        <p ng-show="testAddForm.title.$invalid && !testAddForm.title.$pristine" class="help-block">Title is required.</p>
        <div>
          <input type="button" value="Preview" ng-click="preview(true)" />
          <input type="button" value="Save" ng-disabled="testAddForm.$invalid"/>
        </div>
      </div>
      <div ng-if="previewMode">
        <h2>{{data.title}}</h2>
        <div>
          <input type="button" value="Cancel" ng-click="preview(false)" />
          <input type="button" value="Save" ng-disabled="testAddForm.$invalid"/>
        </div>
      </div>
    </form>
  </body>

</html>

JS:

angular.module('app', []);

angular.module('app').controller('TestController', ['$scope', function($scope) {
  $scope.data = {};
  $scope.previewMode = false;
  $scope.preview = function(show) {
    $scope.previewMode = show;
  };
}]);

回答1:

As a workaround you can try using ng-hide and ng-show instead of ng-if

Example plunkr

<form name="testAddForm" novalidate>
  <div ng-hide="previewMode">
    <input name="title" ng-model="data.title" required />
    <p ng-show="testAddForm.title.$invalid && !testAddForm.title.$pristine" class="help-block">Title is required.</p>
    <div>
      <input type="button" value="Preview" ng-click="preview(true)" />
      <input type="button" value="Save" ng-disabled="testAddForm.$invalid"/>
    </div>
  </div>
  <div ng-show="previewMode">
    <h2>{{data.title}}</h2>
    <div>
      <input type="button" value="Cancel" ng-click="preview(false)" />
      <input type="button" value="Save" ng-disabled="testAddForm.$invalid"/>
    </div>
  </div>
</form>


回答2:

The input field is placed inside the ng-if condition and if ng-if is false, the elements inside are not in the DOM. Since in preview mode your input field is not in the DOM, it is not taken into account while validating the form.

An easy fix would be to use ng-show, like this:

<div ng-show="!previewMode">

Plunkr