Search code examples
angularjsangular-ui-bootstrapbootstrap-modalangularjs-ng-options

binding ng-options with collection of arrays


I have collection of arrays like this:

   $scope.table = {
   hstep: [1, 2, 3],
   mstep: [1, 5, 10, 15, 25, 30]
   };

I want to make a drop down list of these two fields hstep and mstepusing select and ng-options. Here is the html code for ng-options drop down:

   <div class="col-xs-6">
   Hours step is:
   <select class="form-control" ng-model="hstep" ng-options="opt for 
   opt in table.hstep"></select>
   </div>
   <div class="col-xs-6">
   Minutes step is:
   <select class="form-control" ng-model="mstep" ng-options="opt for 
   opt in table.mstep"></select>
   </div>

But the problem is when I use the above code , the drop down doesn't work meaning on clicking the drop down, it wont give a list of the items downward.

Can anyone please tell what is wrong with this ng-options syntax?

P.S. i want to place this drop down in a modal window in angular js.

Here is my js code:

var app = angular.module('myApp', 
    ['ngTouch','ngAnimate','ui.bootstrap']);


app.controller("MainController",
['$scope','$uibModal',function($scope,$uibModal){

$scope.openModal = function(){
$scope.modalInstance = $uibModal.open({
templateUrl: 'modal.html',
controller :'ModalHandlerController',
 size: 'lg',
 });
 }

 $scope.mytime = new Date();
 $scope.table = {
 hstep: [1, 2, 3],
 mstep: [1, 5, 10, 15, 25, 30]
 };
 $scope.hstep = 1;
 $scope.mstep = 15;
 }]);  

app.controller("ModalHandlerController",function($scope,$uibModalInstance)

{  
 $scope.ok = function(){
 $uibModalInstance.close('save');
 }

 });

Solution

  • With angular-ui-bootstrap modal, when you create a modal the scope using in this modal is by default $rootScope, so you wont able to use all scope variable defined in your controller.

    doc:

    scope (Type: $scope) - The parent scope instance to be used for the modal's content. Defaults to $rootScope

    You need to specify the scope to use the controller's scope:

    $scope.table = {
      hstep: [1, 2, 3],
      mstep: [1, 5, 10, 15, 25, 30]
    };
    var modalInstance = $uibModal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      scope: $scope /* <----- HERE to use the controller scope */
    )}
    

    OR use resolve parameter

    you can pass the data in the resolve option parameter

    $scope.table = {
      hstep: [1, 2, 3],
      mstep: [1, 5, 10, 15, 25, 30]
    };
    var modalInstance = $uibModal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      resolve: {
        table: function() {
          return $scope.table;
        }
      }
    });
    

    you can then inject it in your Modal controller:

    app.controller('ModalInstanceCtrl', function($scope, $uibModalInstance, table) {
      $scope.table = table;
    });
    

    https://embed.plnkr.co/NaR7oUNC65ULJTSaKJBh/