AngularJS - 使用控制器中的服务返回的数据和视图来填充下拉列表

时间:2015-08-19 16:37:27

标签: javascript angularjs angularjs-ng-repeat

这是我的index.html

<!doctype html>
<html class="no-js">
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
    <!-- build:css(.) styles/vendor.css -->
    <!-- bower:css -->
    <!-- endbower -->
    <!-- endbuild -->
    <!-- build:css(.tmp) styles/main.css -->
    <link rel="stylesheet" href="styles/main.css">
    <!-- endbuild -->
    <link rel="stylesheet" href="styles/settingsStyles/generalSettings.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

  </head>
  <body ng-app="assignment3App">
    <!--[if lt IE 7]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <!-- Add your site or application content here -->

    <div class="container">
        <h2>General Settings</h2>            
        <table class="table">
          <tbody>
            <tr class="success">
              <td class = "col-xs-3">Language:</td>
              <td class = "col-xs-9">Gmail display language:
                  <select ng-controller = "callServ as langData">
                      <option ng-click = "langData.callServ()"> language </option>
                  </select>
              </td>
            </tr>

            <tr class="danger">
              <td class = "col-xs-3">Phone numbers:</td>
              <td class = "col-xs-9">Default country code:</td>
            </tr>

            <tr class="info">
              <td class = "col-xs-3">Maximum page size: </td>
              <td class = "col-xs-9"> Show conversations per page 
                  <aside> Show contacts per page </aside>
              </td>
            </tr>

            <tr class="success">
              <td class = "col-xs-3">Default reply behavior:</td>
              <td class = "col-xs-9">Reply: 
                  <aside> Reply all:  </aside>
            </tr>

            <tr class="danger">
              <td class = "col-xs-3">Undo Send:</td>
              <td class = "col-xs-9">Enable Undo Send 
                  <aside> Send cancellation period:  </aside>
              </td>
            </tr>

            <tr class="info">
              <td class = "col-xs-3">Signature:  </td>
              <td class = "col-xs-9"> No signature</td>
            </tr>
          </tbody>
        </table>
      </div>

    <!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
     <script>
       !function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=l,A[l]=A[l]||function(){
       (A[l].q=A[l].q||[]).push(arguments)},A[l].l=+new Date,a=n.createElement(g),
       r=n.getElementsByTagName(g)[0],a.src=u,r.parentNode.insertBefore(a,r)
       }(window,document,'script','//www.google-analytics.com/analytics.js','ga');

       ga('create', 'UA-XXXXX-X');
       ga('send', 'pageview');
    </script>

    <!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="bower_components/angular-resource/angular-resource.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-touch/angular-touch.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

        <!-- build:js({.tmp,app}) scripts/scripts.js -->
        <script src="scripts/app.js"></script>
        <script src="scripts/controllers/main.js"></script>
        <script src="scripts/controllers/about.js"></script>
        <script src="scripts/controllers/dropdown.js"></script>
        <script src="scripts/services/extractData.js"></script>
        <script src="scripts/services/fetchData.js"></script>
        <!-- endbuild -->
</body>
</html>

这是我的控制器dropdown.js

(function() {
    'use strict';

    var callServ = function (getData) {
        getData.getLanguages();
        };

    angular.module('assignment3App')
      .controller ('callServ', ['getData', callServ]);      
}());

调用其他服务以获取json数据的服务extractData.js

(function() {
  'use strict';

  var getData = function (fetchDataService) {
      this.getLanguages = function() {

             fetchDataService.getContent()
              .then(function (returnedData) {
                    console.log(returnedData.data.languages[0]);
                  });
              };   
      };    

      angular.module('assignment3App')
        .service ('getData', ['fetchDataService', getData]);
}());

获取JSON数据的服务fetchData.js

(function() {
  "use strict";

  var fetchDataService = function($http) {
      this.getContent = function() {
        return $http({
            method : 'get',
            url : '../../data/languages.json'
          });
      };
  };

  angular.module('assignment3App')
    .service ('fetchDataService', fetchDataService);
}());

我想在选择菜单中填充JSON文件中的语言作为选项。

language.json

{
    "languages": [
        "Afrikaans",
        "Albanian",
        "Arabic",
        "Armenian",
        "Basque",
        "Bengali",
        "Catalan",
        "Cambodian",
        "Chinese (Mandarin)",
        "German",
        "Greek",
        "Gujarati",
        "Hebrew",
        "Icelandic" ,
        "Maori" ,
        "Marathi",
        "Mongolian",
        "Serbian",
        "Slovak",
        "Slovenian",
        "Spanish",
        "Swahili",
        "Swedish" ,
        "Tamil" ,
        "Tatar" ,
        "Telugu"
    ] 
}

我有以下问题:

1)如何访问控制器中文件returnedData中的extractData.js变量?

2)如何在index.html中的选项元素上使用ng-repeat来显示下拉列表中的所有语言?我应该使用$ index来获取视图中JSON数组的每个元素吗?

3)根据用户选择的语言,当他点击提交按钮时,我希望所选语言存储在另一个服务中。有没有人有任何想法?

更新 - 问题2

我可以使用ng-options填充下拉菜单。在我的控制器中,我将languages变量更改为仅保留languages的数组。以下是我更新的index.html和控制器。

<!doctype html>
<html class="no-js">
  <head>
    <meta charset="utf-8">
    <title> Settings Page </title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
    <!-- build:css(.) styles/vendor.css -->
    <!-- bower:css -->
    <!-- endbower -->
    <!-- endbuild -->
    <!-- build:css(.tmp) styles/main.css -->
    <link rel="stylesheet" href="styles/main.css">
    <!-- endbuild -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles/settingsStyles/generalSettings.css">

  </head>
  <body ng-app="assignment3App">
    <!--[if lt IE 7]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <!-- Add your site or application content here -->

    <div class="container">
        <h3>General Settings</h3>      

        <table class="table">
          <tbody>
            <tr class="success" ng-controller = "callServ">
              <td class = "col-xs-3">Language:</td>
              <td class = "col-xs-9">Gmail display language:
                  <select ng-model = "selectedLang" ng-options="language for language in languages">
                      <option value = ""> Choose a language </option>
                  </select>
              </td>
            </tr>

            <tr class="danger">
              <td class = "col-xs-3">Phone numbers:</td>
              <td class = "col-xs-9">Default country code:
                  <select>
                      <option> Country code </option>
                  </select>
              </td>
            </tr>

            <tr class="info">
              <td class = "col-xs-3">Maximum page size: </td>
              <td class = "col-xs-9"> Show conversations per page 
                  <select>
                      <option> 10 </option>
                  </select>

                  <aside id = "pageSize"> Show contacts per page 
                        <select>
                            <option> 20 </option>
                        </select>
                  </aside>

              </td>
            </tr>

            <tr class="success">
              <td class = "col-xs-3">Default reply behavior:</td>
              <td class = "col-xs-9">
                  <input type = "radio" name = "replySetting" id = "reply" checked> 
                  <label for="reply"> Reply </label>

                  <aside> 
                        <input type = "radio" name = "replySetting" id = "replyAll"> 
                        <label for="replyAll"> Reply all</label> 
                  </aside>
            </tr>

            <tr class="danger">
              <td class = "col-xs-3">Undo Send:</td>
              <td class = "col-xs-9" ng-controller = "undoSendController as undoSend">
                  <input type = "checkbox" id = "undoSend" ng-click = "undoSend.displayCancelPeriod()"> 
                  <label for="undoSend"> Enable Undo Send  </label> 

                  <aside ng-show = "undoSend.cancelPeriod" ng-cloak> Send cancellation period:  
                      <select>
                            <option> 10 </option>
                      </select>
                  </aside>
              </td>
            </tr>

            <tr class="info" ng-controller = "signatureController as signature">
              <td class = "col-xs-3">Signature:  </td>
              <td class = "col-xs-9"> 
                  <input type = "radio" name = "signature" ng-click = "signature.disableTextarea()" id = "noSignature" checked> 
                  <label for="noSignature"> No signature </label> 
                    <div class="span12" >
                          <input type = "radio" name = "signature" ng-click = "signature.enableTextarea()" id = "signature">
                          <textarea class="field span6" id="textarea" rows="6" cols = "50" placeholder="Enter a signature" ng-disabled = "signature.typeSignature"></textarea>
                    </div>
              </td>
            </tr>
          </tbody>
        </table>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary">Save changes</button>
          <button type="button" class="btn">Cancel</button>
        </div>
      </div>

    <!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
     <script>
       !function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=l,A[l]=A[l]||function(){
       (A[l].q=A[l].q||[]).push(arguments)},A[l].l=+new Date,a=n.createElement(g),
       r=n.getElementsByTagName(g)[0],a.src=u,r.parentNode.insertBefore(a,r)
       }(window,document,'script','//www.google-analytics.com/analytics.js','ga');

       ga('create', 'UA-XXXXX-X');
       ga('send', 'pageview');
    </script>

    <!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="bower_components/angular-resource/angular-resource.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-touch/angular-touch.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

        <!-- build:js({.tmp,app}) scripts/scripts.js -->
        <script src="scripts/app.js"></script>
        <script src="scripts/controllers/main.js"></script>
        <script src="scripts/controllers/about.js"></script>
        <script src="scripts/controllers/dropdown.js"></script>
        <script src="scripts/controllers/undoSend.js"></script>
        <script src="scripts/controllers/signature.js"></script>
        <script src="scripts/services/promise.js"></script>
        <script src="scripts/services/callJson.js"></script>
        <!-- endbuild -->
</body>
</html>

dropdown.js

(function() {
    'use strict';

    var callServ = function (getData, $scope) {
        getData.getLanguages()
            .then(function(data){
                    $scope.languages = data.languages;
        });
    };

    angular.module('assignment3App')
      .controller ('callServ', ['getData', '$scope', callServ]);        
}());

1 个答案:

答案 0 :(得分:3)

首先,您将使用承诺从服务中返回数据:

(function() {
  'use strict';

  var getData = function (fetchDataService) {
      this.getLanguages = function() {

             return fetchDataService.getContent()
              .then(function (returnedData) {
                    return returnedData.data;
                    //console.log(returnedData.data.languages[0]);
                  });
              };   
      };    

      angular.module('assignment3App')
        .service ('getData', ['fetchDataService', getData]);
}());

然后,您将从返回的promise中获取数据并将其添加到控制器的范围中:

(function() {
    'use strict';

    //this will be the select value
    $scope.selectedLanguage = '';

    $scope.setLanguage = function(){
        //this is called when the submit button is clicked
        yourService.languageChanged($scope.selectedLanguage);
    };

    var callServ = function (getData) {
        getData.getLanguages().then(function(data){
            //data = returnedData.data
            $scope.languages = data;
        });
    };

    angular.module('assignment3App')
      .controller ('callServ', ['getData', callServ]);      
}());

然后,您可以将选项附加到选择using ng-options

<select ng-options="language for language in languages"
    ng-model="selectedLanguage">
</select>
<button type="button" ng-click="setLanguage()">Submit</button>