1

Я только начинаю с Углового и подбегаю к некоторым препятствиям в своем понимании некоторых основных концепций. Чтобы лучше ознакомиться с этой новой структурой, я пытаюсь создать тривиальное приложение: «Не так ли?». Я представляю пользователю два вопроса, они выбирают один, я выделяю их выбор и показываю, сколько голосов у каждого вопроса у предыдущих пользователей.Изолируйте только тот элемент, который был нажат.

Это звучит просто, но я все еще застрял в системе jQuery; Я хочу выбрать элемент на основе $ (this) или $ ("# id").

У меня есть фабрика с массивом объектов вопросов. Каждый объект имеет ключ firstQuestion и secondQuestion, который сопоставляет вопрос, а также ключи firstVotes и secondVotes с соответствующим количеством голосов. Я использую QuestionsCtrl для управления областью действия и принятия мер, когда пользователь делает выбор.

Вот мой index.html файл:

<!DOCTYPE html> 

<html> 

<head lang="en"> 
    <meta charset="utf-8"> 
    <title>Would You Rather?</title> 
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
</head> 
<body> 
    <div class="container" ng-app="wouldYouRatherApp"> 
    <div ng-controller="QuestionsCtrl"> 
     <div class="container"> 
     <div class="row text-center"> 
      <h1 class="col-md-12">Would you rather...</h1> 
     </div> 
     <div class="row text-center"> 
      <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-{{buttonClass}}" ng-click="recordAnswer('first')">{{question.firstQuestion}}</h2> 
      <span class="badge" ng-show="badge.show">{{question.firstVotes}}</span> 
      </div> 
     </div> 
     <div class="row text-center"> 
      <h3 class="col-md-12"><small>or</small></h3> 
     </div> 
     <div class="row text-center"> 
      <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-{{buttonClass}}" ng-click="recordAnswer('second')">{{question.secondQuestion}}</h2> 
      <span class="badge" ng-show="badge.show">{{question.secondVotes}}</span> 
      </div> 
     </div> 
     <br> 
     <div class="row text-center"> 
      <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-primary" ng-show="showNextQuestion" ng-click="nextQuestion()">Next Question&nbsp;&nbsp;<span class="glyphicon glyphicon-forward"></span></h2> 
      </div> 
     </div> 
     </div> 
    </div> 
    </div> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script> 
    <script type="text/javascript" src="./main.js"></script> 
</body> 
</html> 

А вот мои main.js файл:

var app = angular.module("wouldYouRatherApp", []); 

app.factory("Badges", function() { 
    return {show: false} 
}) 

app.factory("Questions", function() { 
    var Questions = [{ 
     firstQuestion: "Ride a horse?", 
     firstVotes: 101, 
     secondQuestion: "Ride a cowboy?", 
     secondVotes: 212 
    }, 
    { 
     firstQuestion: "Kiss a frog?", 
     firstVotes: 13, 
     secondQuestion: "Lick a slug?", 
     secondVotes: 23 
    }, 
    { 
     firstQuestion: "Play Monopoly?", 
     firstVotes: 12, 
     secondQuestion: "Play Risk?", 
     secondVotes: 17 
    }]; 
    return Questions; 
}) 

app.controller("QuestionsCtrl", function($scope, Badges, Questions) { 
    $scope.question = Questions.shift(); 
    $scope.buttonClass = 'default'; 
    $scope.showNextQuestion = false; 
    $scope.badge = Badges; 

    $scope.recordAnswer = function(choice) { 
     console.log("User chose: " + choice); 
     $scope.buttonClass = 'success'; 
     // increment votes badge 
     $scope[choice+'Votes'] += 1; 
     Badges.show = true; 
     $scope.showNextQuestion = true; 
    } 

    $scope.nextQuestion = function() { 
     $scope.question = Questions.shift(); 
     Badges.show = false; 
     $scope.buttonClass = 'default'; 
     $scope.showNextQuestion = false; 
    } 
}) 

Живой пример можно найти здесь: http://jsfiddle.net/t99TL/2/

Ожидаемое поведение приложения выглядит следующим образом:

  1. Два вопроса представлены пользователю.
  2. Пользователь нажимает на одну из кнопок.
  3. Этот вопрос выделен. И значок голосов увеличивается. Отображаются значки обоих голосов.
  4. Кнопка «Следующий вопрос» предоставляется пользователю.
  5. Когда он нажимает кнопку «Следующий вопрос», загружается новый вопрос.

Я чувствую, что мне, вероятно, нужно создать директиву для каждого отдельного вопроса ... но я не уверен, как начать, или если я даже на правильном пути. Любые советы по препятствиям, с которыми я столкнусь в будущем, очень ценятся (т. Е. Обновление атрибута голосов для вопроса и т. Д.).

ответ

1

Есть много изменений, чтобы заставить его работать так, как вы хотите. Этот код не идеален, просто демонстрация.

HTML:

<div class="container" ng-app="wouldYouRatherApp"> 

    <div ng-controller="QuestionsCtrl"> 
    <div class="container"> 
     <div class="row text-center"> 
     <h1 class="col-md-12">Would you rather...</h1> 
     </div> 
     <div class="row text-center"> 
     <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-{{question.firstQuestion.buttonClass}}" ng-click="recordAnswer(question.firstQuestion)">{{question.firstQuestion.text}}</h2> 
      <span class="badge" ng-show="badge.show">{{question.firstQuestion.votes}}</span> 
     </div> 
     </div> 
     <div class="row text-center"> 
     <h3 class="col-md-12"><small>or</small></h3> 
     </div> 
     <div class="row text-center"> 
     <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-{{question.secondQuestion.buttonClass}}" ng-click="recordAnswer(question.secondQuestion)">{{question.secondQuestion.text}}</h2> 
      <span class="badge" ng-show="badge.show">{{question.secondQuestion.votes}}</span> 
     </div> 
     </div> 
     <br> 
     <div class="row text-center"> 
     <div class="col-md-12"> 
      <h2 class="btn btn-lg btn-primary" ng-show="showNextQuestion" ng-click="nextQuestion()">Next Question&nbsp;&nbsp;<span class="glyphicon glyphicon-forward"></span></h2> 
     </div> 
     </div> 
    </div> 

    </div> 

JS:

var app = angular.module("wouldYouRatherApp", []); 


app.factory("Badges", function() { 
    return {show: false} 
}) 


app.factory("Questions", function() { 
    var Questions = [{ 
     firstQuestion: { 
      text:"Ride a horse?", 
      votes: 101, 
      buttonClass : 'default' 
     }, 
     secondQuestion: { 
      text:"Ride a cowboy?", 
      votes: 212, 
      buttonClass : 'default' 
     }, 
    }, 
    { 
     firstQuestion: { 
      text:"Kiss a frog?", 
      votes: 13, 
      buttonClass : 'default' 
     }, 
     secondQuestion: { 
      text:"Lick a slug?", 
      votes: 23, 
      buttonClass : 'default' 
     } 
    }, 
    { 
     firstQuestion: { 
      text:"Play Monopoly?", 
      votes: 12, 
      buttonClass : 'default' 
     }, 
     secondQuestion: { 
      text:"Play Risk?", 
      votes: 17, 
      buttonClass : 'default' 
     } 
    }]; 
    return Questions; 
}) 


app.controller("QuestionsCtrl", function($scope, Badges, Questions) { 
    $scope.question = Questions.shift(); 
    $scope.buttonClass = 'default'; 
    $scope.showNextQuestion = false; 
    $scope.badge = Badges; 

    $scope.recordAnswer = function(choice) { 
     choice.buttonClass = 'success'; 
     choice.votes++; 
     Badges.show = true; 
     $scope.showNextQuestion = true; 
    } 

    $scope.nextQuestion = function() { 
     $scope.question.firstQuestion.buttonClass = "default"; 
     $scope.question.secondQuestion.buttonClass = "default"; 

     $scope.question = Questions.shift(); 
     Badges.show = false; 
     $scope.showNextQuestion = false; 
    } 
}) 

DEMO

+0

Это работало отлично, спасибо! – Abundnce10

Смежные вопросы