Angular和链接下拉列表不保存数据

时间:2015-09-14 16:42:42

标签: javascript html angularjs

我试图让我的视图包含3个下拉列表和一个提交按钮。我已经弄清楚如何在包含数据之前不显示下拉列表。我已经想出如何在更改上一个下拉列表时加载它。但是,我有几个问题。这是代码,然后我将解释问题:

观点:

<div ng-controller="UserCtrl">
    <div class="row" ng-show="$parent.loggedin">
        <div class="col-sm-3">
            <div class="form-group">
                <label for="lawType">Type of Law</label>
                <select class="form-control" id="lawType" ng-change="getCourthouse();" data-ng-model="typeoflaw">
                    <option value="0" selected>--Select a Type of Law--</option>
                    <option ng-repeat="type in typeoflaw" value="{{ type.LitigationCode}}">{{ type.LitigationType }}</option>
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group" data-ng-show="courtHouse.length">
                <label for="courtHouse">Courthouse</label>
                <select class="form-control" id="courtHouse" data-ng-model="courtHouse" ng-change="getCourtroom();">
                    <option ng-repeat="bldg in courtHouse track by $index" value="{{ bldg.Loc_ID }}">{{ bldg.Loc_Name }}</option>
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group" data-ng-show="courtRoom.length" data-ng-model="courtRoom">
                <label for="courtRoom">Department</label>
                <select class="form-control" id="courtRoom">
                    <option ng-repeat="room in courtRoom" value="{{ room.CourtRoom }}">{{ room.CourtRoom }}</option>
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="favorite-button">
                <button class="btn  btn-primary pull-left">Add Favorite</button>
            </div>
        </div>
    </div>
</div>

控制器:

JBenchApp.controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', 'UserService', 
  function ($scope, $routeParams, $http, $filter, UserService) {
          // Get the preferences information
      /**UserService.loadType()
      .then(function (lawtypes) {
          $scope.typeoflaw = lawtypes;
      });**/



      $http.get('http://10.34.34.46/BenchViewServices/api/Litigation').success(function (response) {
          $scope.typeoflaw = response;
      });

      //$scope.courtHouse = [{ "Loc_ID": "0", "Loc_Name": "-- Select a Type of Law to Get Courthouse List --" }];
      //$scope.courtHouse = [];
      //$scope.courtRoom = [];

      $scope.getCourthouse = function () {
          var e = document.getElementById("lawType");
          $scope.typeoflawId = e.options[e.selectedIndex].value;
          console.log($scope.typeoflawId);
          $http.get('http://10.34.34.46/BenchViewServices/api/CourtDept/' + $scope.typeoflawId).success(function (response) {
              $scope.courtHouse = response;

          }).error(function (status, data) {
              console.log("error trapped");
          });
      }

      $scope.getCourtroom = function () {
          var e = document.getElementById("courtHouse");
          $scope.courtHouseId = e.options[e.selectedIndex].value;
          console.log($scope.courtHouseId);
          $http.get('http://10.34.34.46/BenchViewServices/api/CourtDept/' + $scope.typeoflawId + "/" + $scope.courtHouseId).success(function (response) {
              $scope.courtRoom = response;

          }).error(function (status, data) {
              console.log("error trapped");
          });
      }

      $scope.SavePreferences = function () {

      };

  }]);

问题:

  1. 当第一个下拉列表,法律类型,加载时,它没有按照我在标记中请求选择的“ - 选择一种法律 - ”。实际上,只有一个空条目位于“选择一种法律”之上,默认选择它。如何在加载时选择列表中的初始条目?
    1. 当第一个下拉列表被更改(进行选择)时,它会加载第二个下拉列表,但第一个下拉列表除了前面提到的空白行和“选择一种法律类型”条目之外是空的。如何使其保存那里的数据并正确显示所选项目?
    2. 当第二个下拉列表更改时,它会加载第三个下拉列表,但与第一个下拉列表有相同的问题...它会自行清空,也不会显示用户所做的选择。如何使其自身不空并仍然显示用户所做的选择?
  2. 谢谢!

2 个答案:

答案 0 :(得分:0)

我解决了在一个或多个控制器之间传递数据的问题的方法是使用服务。 所以这是一个服务的例子

var NameService = function () {
    var service = this;
    service.property= value;
    service.getProperty = function () {
        return property;
    }
};
ngapp.service('NameService', NameService);

关于它的一个很酷的事情是你可以在你的控制器中注入你的服务

appcontroller.$inject = ['$scope', '$http', 'NameService'];
$.ajaxSetup({
    async: false
});
var NameCtrl = function ($scope, $http, NameService) {
    var Property = NameService.Property;
    $scope.update = function () {
        NameService.Property= $scope.Properties.selectedProperty.PropertyId;
    }
};
appcontroller.controller('NameCtrl', NameCtrl);

答案 1 :(得分:0)

以下是我最终解决问题的方法。

在视图中:

<div ng-controller="UserCtrl">
    <div class="row" ng-show="$parent.loggedin">
        <div class="col-sm-3">
            <div class="form-group">
                <label for="lawType">Select a Type of Law</label>
                <select class="form-control" id="lawType" name="lawType" ng-change="getCourthouse();" ng-model="typeoflaw.LitigationType" ng-options="typeoflaw.LitigationType for typeoflaw in typeoflaw track by typeoflaw.LitigationCode" required>
                    <option value="">--Select a Type of Law--</option>
                   <!-- <option value="0" selected>--Select a Type of Law--</option>
                    <option ng-repeat="type in typeoflaw" value="{{ type.LitigationCode}}">{{ type.LitigationType }}</option>-->
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group" ng-show="courtHouse.length">
                <label for="courtHouse">Select a Courthouse</label>
                <select class="form-control" id="courtHouse" name="courtHouse" ng-model="courtHouse.Loc_ID" ng-change="getCourtroom();" ng-options="courtHouse.Loc_Name for courtHouse in courtHouse track by courtHouse.Loc_Name" required>
                    <option value="">--Select a Courthouse--</option>
                    <!--<option ng-repeat="bldg in courtHouse track by $index" value="{{ bldg.Loc_ID }}">{{ bldg.Loc_Name }}</option>-->
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group" ng-show="courtRoom.length">
                <label for="courtRoom">Select a Department</label>
                <select class="form-control" id="courtRoom" name="courtRoom" ng-model="courtRoom.CourtRoom" ng-options="courtRoom.CourtRoom for courtRoom in courtRoom track by courtRoom.CourtRoom" required>
                    <option value="">--Select a Department--</option>
                    <!-- <option ng-repeat="room in courtRoom" value="{{ room.CourtRoom }}">{{ room.CourtRoom }}</option>-->
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="favorite-button" ng-show="courtRoom.length">
                <button class="btn  btn-primary pull-left" ng-click="SavePreferences();">Add Favorite</button>
            </div>

        </div>
    </div>
    <div class="row" ng-show="userPreferences.length">
        <div class="col-sm-12 favorite-header">
            <h2>Your Saved Favorites</h2>
        </div>
        <div class="col-sm-12 favorite-filter">
            <input type="text" ng-model="query" placeholder="Filter your favorites list" />
        </div>
    </div>
    <div class="row" ng-show="userPreferences.length">
        <div class="col-sm-3 favorite-column-title">
            Courthouse
        </div>
        <div class="col-sm-3 favorite-column-title">
            Department
        </div>
        <div class="col-sm-3 favorite-column-title">
            Type of Law
        </div>
        <div class="col-sm-3 favorite-column-title">
            Default
        </div>
    </div>
    <div class="row" ng-show="userPreferences.length" ng-model="userPreferences" ng-repeat-start="userPreference in userPreferences | filter:query | orderBy: ['LocName', 'CourtRoom']">
        <div class="col-sm-3">
            <span class="get-path" ng-click="setPathValues(userPreference.LitigationCode, userPreference.LocID, userPreference.CourtRoom);">{{ userPreference.LocName }} ({{ userPreference.CourtRoom}})</span>
</div>
        <div class="col-sm-3">
            {{ userPreference.CourtRoom}}
        </div>
        <div class="col-sm-3">
            {{ userPreference.LitigationType }}
        </div>
        <div class="col-sm-3">
            <span ng-if="showDefaultIcon(userPreference.IsDefault);" class="glyphicon glyphicon-ok green-check" data-toggle="tooltip" data-placement="top" title="This is your default favorite and it cannot be deleted. Please mark another favorite as your default before attempting to delete this one." tooltip></span>
            <span ng-if="!showDefaultIcon(userPreference.IsDefault);" class="glyphicon glyphicon-star-empty red-star" ng-click="setAsDefault(userPreference.PreferenceID, userPreference.LitigationCode, userPreference.LocID, userPreference.CourtRoom);" data-toggle="tooltip" data-placement="top" title="Mark this favorite as your default." tooltip></span>
            <span ng-if="!showDefaultIcon(userPreference.IsDefault);" class="glyphicon glyphicon-remove delete-icon" ng-click="deletePreference(userPreference.PreferenceID);" data-toggle="tooltip" data-placement="top" title="Delete this favorite." tooltip></span>
        </div>
    </div>
    <div ng-repeat-end></div>
</div>

在控制器中:

JBenchApp.controller('UserCtrl', ['$scope', '$routeParams', '$http', '$filter', '$window', 'HoldState', 
  function ($scope, $routeParams, $http, $filter, $window, HoldState) {


      $scope.isDefault = false;


      $http.get('http://10.34.34.46/BenchViewServices/api/Litigation').success(function (response) {
          $scope.typeoflaw = response;
      });

      $scope.getCourthouse = function () {
          $scope.typeoflawId = $scope.typeoflaw.LitigationType;
          console.log($scope.typeoflawId);
          $scope.courtRoom = [];
          $http.get('http://10.34.34.46/BenchViewServices/api/CourtDept/' + $scope.typeoflawId.LitigationCode).success(function (response) {
              $scope.courtHouse = response;

          }).error(function (status, data) {
              console.log("error trapped");
          });
      }

      $scope.getCourtroom = function () {
          var e = document.getElementById("courtHouse");
          $scope.courtHouseId = $scope.courtHouse.Loc_ID;
          console.log($scope.courtHouseId);
          $http.get('http://10.34.34.46/BenchViewServices/api/CourtDept/' + $scope.typeoflawId.LitigationCode + "/" + $scope.courtHouseId.Loc_ID).success(function (response) {
              $scope.courtRoom = response;

          }).error(function (status, data) {
              console.log("error trapped");
          });
      }

      $scope.LoadPreferences = function () {

          $http.get('http://10.34.34.46/BenchViewServices/api/UserPreference/dpeng').success(function (response) {
              $scope.userPreferences = response;
          }).error(function (status, data) {
              console.log("error trapped");
          });
      }

      $scope.SavePreferences = function () {
          $scope.userid = 'dpeng';
          $scope.departmentNumber = $scope.courtRoom.CourtRoom;
          $scope.newPreference = {
              "PreferenceID": "0",
              "UserID": $scope.userid,
              "LocID": $scope.courtHouseId.Loc_ID,
              "CourtRoom": $scope.departmentNumber.CourtRoom,
              "IsDefault": $scope.isDefault,
              "LitigationCode": $scope.typeoflawId.LitigationCode
          };
          $http({
              method: 'POST',
              url: 'http://10.34.34.46/BenchViewServices/api/UserPreference/Post',
              data: $scope.newPreference,
              headers: {
                  'Content-Type': 'application/json'
              }
          }).then(function(response) {
              LoadPreferences();
              console.log(response);
          }, function(response) {
              console.log(response.status + " -- " + response.data + " -- " + response.statusText);
          });
      }

      $scope.showDefaultIcon = function (theStatus){
          return theStatus;
      }

      $scope.showSetAsDefaultIcon = function (theStatus) {
          if (theStatus) {
              return false;
          } else {
              return true;
          }
      }

      $scope.setAsDefault = function (prefId, LitCode, LocID, Dept) {
          alert("setAsDefault function is called")
          var data = {
              "LitigationCode": LitCode,
              "LocID": LocID,
              "CourtRoom": Dept,
              "IsDefault": true
          };

          $http.put(' http://10.34.34.46/BenchViewServices/api/UserPreference/Put/' + prefId, data)
          .then(function (response) {
              LoadPreferences();
              console.log(response);
          }, function (response) {
              console.log(response.status + " -- " + response.data + " -- " + response.statusText);
          });
      }

      $scope.deletePreference = function (prefId) {
          $http.delete('http://10.34.34.46/BenchViewServices/api/UserPreference/Delete/' + prefId);
          LoadPreferences();
      }

      $scope.setPathValues = function (LawType, Bldg, Dept) {
          HoldState.setTypeOfLaw(LawType);
          HoldState.setCourthouse(Bldg);
          HoldState.setDepartment(Dept);
          var a = HoldState.getTypeOfLaw();
          var b = HoldState.getCourthouse();
          var c = HoldState.getDepartment();
          //alert('Law: ' + a + ' Courthouse: ' + b + ' Department: ' + c);
          $window.location.href = 'calendar';
      }

      $scope.LoadPreferences();

  }]);

关键是ng-options:

ng-model="courtHouse.Loc_ID" " ng-options="courtHouse.Loc_Name for courtHouse in courtHouse track by courtHouse.Loc_Name"

当我这样设置时,3个下拉菜单完美同步。