2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ng-if・ng-show/hideの違いでrequiredの挙動が異なる

Last updated at Posted at 2017-09-23

入力フォームをAngularJSを用いて実装した際に困ったことを紹介します。

必須入力と表示非表示

以下のような入力フォームを構成するhtmlと、ボタンが押されると呼び出されるfunctionを定義しました。

sample.html
<!DOCTYPE html>
<html ng-app='App'>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
   <script type="text/javascript" src="controller.js"></script>
  <title>test</title>
</head>
<body ng-controller="AppController">
  <form name="form" ng-submit="hoge()">
    <input type="text" ng-show="true" required>
    <input type="text" ng-show="false" required>
    <button type="submit" >send</button>
  </form>
</body>
</html>
sample.js
var app = angular.module('App', []);

app.controller('AppController', function($scope){
  $scope.hoge = function(){
    console.log('hoge is called');
  }
});

するとこんな感じに。ng-show="false"を指定しているinputは表示されません。またそれぞれのinput要素でrequiredによる必須入力を指定しています。
test.jpg

フォームに適当な文字を入力し、sendボタンを押すと、上で定義したfunctionが実行されるはず...だと思ったのですが、実行されず。ng-show="false"を指定しているinputのrequiredが効いてしまっています。

次に同様な機能のディレクティブ、ng-ifを使ってみます。先ほどのinput要素を以下のように書き換えます。

    <input type="text" ng-if="true" required>
    <input type="text" ng-if="false" required>

先ほど同様な見た目になり、文字を入力しsendを押すと、functionが実行されログが出力されます。

ng-if・ng-show/hideの違い

先ほどの事象が起きるまでng-if、ng-showの違いを理解していませんでしたが、調べると次のような違いがあります。

  • ng-if:DOMの追加と削除
  • ng-show/hide : CSSによる表示非表示切り替え

したがって、ng-show="false"を指定しただけではDOMとして要素が存在しておりrequiredが効く状態になっていました。

必須入力を評価できるディレクティブ:ng-required

必須入力を動的に変化させたい場合、ng-requiredというディレクティブを使うことで実現できます。イコールで評価式(true,false)を指定すると、trueの評価のときだけ必須入力となります。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?