简体   繁体   中英

How to display user's select choice in angularjs?

How do I display an option in a paragraph

when a user selects one of the options?

Here is what I have so far:

<select ng-model="model.id" convert-to-number>
  <option value="0">Soccer</option>
  <option value="1">Basketball</option>
  <option value="2">Tennis</option>
  <option value="3">Baseball</option>
 </select>

 <p> Your choice is [user's choice goes here]! </p>

Basically, how would I get it to display a user's choice in a <p> ? And how do I keep it there?

If statements, switches, append? I've been stuck on how to do this

Controller:

.run(function($rootScope) {
  $rootScope.model = { id: 2 };
})
.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return parseInt(val, 10);
      });
      ngModel.$formatters.push(function(val) {
        return '' + val;
      });
    }
  };
});

You simply bind it to a model using the binding expression {{ }} .

<p> Your choice is {{ yourModel }} </p>

This is one way binding, if you need two way binding, then you can use ng-model to bind it.

I did a simple example, I managed to get it to bind.

HTML

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

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

<body ng-controller="MainController">
  <select ng-model="model.id" convert-to-number="" selected="selected">
    <option value="0">Soccer</option>
    <option value="1">Basketball</option>
    <option value="2">Tennis</option>
    <option value="3">Baseball</option>
  </select>
  <p> Your choice is {{ model.id }}! </p>
</body>

</html>

JS

(function() {
    "use strict";

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

    app.controller("MainController", ["$scope", MainController]);

    function MainController($scope) {
         $scope.model = {
           id: 1
         };
    }

}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM