LoginSignup
1
1

More than 5 years have passed since last update.

$scopeを使わずにFormControllerを取得する

Posted at

概要

AngularJSでJavaScriptから$setDirty$setPristineを使う方法です。
たまに忘れてしまうので、メモとして残しておきます。

HTML側

<div ng-controller="SampleController as ctrl">
  <form name="ctrl.form">
    <!-- ここからフォーム
    <input type="text" ng-model="ctrl.text">
    <button type="button" ng-click="ctrl.save()" ng-disabled="ctrl.form.$pristine">Save</button>
    -->
  </form>
</div>

ControllerAsで指定したコントローラ名をフォームの名前の前に付けましょう。
この例では「ctrl.form」でアクセスしています。

JavaScript側

// ↓コントローラの書き方
// https://github.com/johnpapa/angular-styleguide/blob/master/a1/i18n/ja-JP.md
(function(){
    'use strict'

    // コントローラを登録
    angular
        .module('app')
        .controller('SampleController', Controller);

    // DI
    SettingController.$inject = ['$log'];

    // コントローラ
    function Controller($log) {
        // ビューモデル
        var vm = this;
        vm.save = save;

        // 保存
        function save() {
            $log.debug('保存');
            vm.form.$setPristine(); // 未入力状態に戻す
        }
    }
})();

this(を代入した変数名)とHTML側で設定したフォーム名を使います。
この例では「vm.form」でアクセスしています。

1
1
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
1
1