0

私はAngularを初めて使用し、すべてのチュートリアルを読みましたが、独自のアプリの構築を始めたばかりなので、学習曲線の急勾配にいます!

アンケートを作成しています。一度に 1 つの質問を表示したいと思います (質問への回答に応じて)。

私の質問は、コントローラーでこれを構成する最もクリーンな方法についてです。

現在、私の HTML は次のようになっています。

<div ng-show="showIntro"> <!-- Intro, shown by default -->
  Intro
  <button ng-click="nextIntro">Next</button>
</div>

<div ng-show="showQ1"> <!-- Question 1, shown after the user clicks Next -->
  Question 1

<label class="checkbox-inline"> <!-- Radio buttons for user response -->
  <input type="radio" name="ast-adh-p1-q1" ng-model="q1aVal" 
   ng-change='answerQ1(q1aVal)' value="yes"> Yes
</label>
<label class="checkbox-inline">
  <input type="radio" name="ast-adh-p1-q1" ng-model="value" 
  ng-change='answerQ1(value)' value="no"> No
</label>

 <div ng-show="showQ1extra"> <!-- Shown if user answers yes to question 1 -->
   some extra content if the user answers yes to question 1 here
 </div>

 <button ng-click="nextQ1">Next</button>

</div>

<div ng-show="showQ2"> <!-- Question 2, shown after completing question 1 -->
  Question 2 ...
</div>

そして、私のコントローラーは次のようになります。

    $scope.showIntro = true;
    $scope.showQ1 = false;
    $scope.showQ1extra = false;
    $scope.showQ2 = false;

    $scope.nextIntro = function() {
      $scope.showIntro = false;
      $scope.showQ1 = true;
    }

    $scope.answerQ1 = function(q1aVal) {
      $scope.showQ1extra = (q1aVal === 'yes') ? true : false;
    }

    $scope.nextQ1 = function() {
      $scope.showQ1 = false;
      $scope.showQ1extra = false;
      $scope.showQ2 = true;
    }

動作しますが、洗練されておらず、スケーラブルではありません。それを行うためのより賢明なAngularの方法はありますか?

私自身の感覚で$scope.activeSectionは、数値であり、最初は 0 に設定されているパラメーターが必要であると考えています。その後、 などshowIntroを返す必要があり、毎回 1 ずつ増加する単一のボタンが必要です。それは Angular に適した方法のように聞こえますか?$scope.activeSection === 0NextactiveSection

更新: サンプル コード付きのプランカーを次に示します: http://plnkr.co/edit/Ursyhc7YJYbJS5OCGYEr?p=preview

4

1 に答える 1

1

これは、"ngSwitch" ディレクティブを使用して非常に少量のコードで解決できます。

HTML:

<div ng-switch="step">
    <div ng-switch-when="1">
        <p>This is step 1</p>
        <button ng-click="setStep(2)" class="btn btn-success">Go to step 2</button>
    </div>
    <div ng-switch-when="2">
        <p>This is step 2</p>
        <button ng-click="setStep(3)" class="btn btn-success">Go to step 3</button>
    </div>
    <div ng-switch-when="3">
        <p>This is step 3</p>
        <button ng-click="setStep(1)" class="btn btn-success">Back to start</button>
    </div>
</div>

そしてあなたのコントローラーで:

$scope.step = 1;
$scope.setStep = function (num) {
    $scope.step = num;
};

ここで結果を確認できます: http://jsfiddle.net/Gg92r/

于 2013-11-12T16:34:13.993 に答える