简体   繁体   中英

Create div dynamically on option select in AngularJS

I am trying to create div s dynamically using option select value but ng-repeat not working. Let me know what I am doing wrong here.

Following is my HTML code -

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <title>Select Example - AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
    <script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
    <select id="shiftnumbers"
            ng-model="event.shiftnumber"
            ng-options="timeslot.value as timeslot.name for timeslot in shiftnumbers"
            ng-init="event.shiftnumber = shiftnumbers[0].value"
            class="btn">
    </select>
    <div ng-repeat="event.shiftnumber">{{event.shiftnumber}}</div>
</body>
</html>

Following is my Script -

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

myApp.controller("myCtrl", function($scope){

    $scope.shiftnumbers = [];
    for(var i=0; i< 23; i++) {
        $scope.shiftnumbers.push({name: i, value: i});
    }
});

PLNKR LINK - http://plnkr.co/edit/UruYYbXrTgxqXadIb8A3?p=preview

Create a new array selectedShiftnumbers to store selected values. Then use ngRepeat to list it.

HTML

<select id="shiftnumbers"
        ng-model="event.shiftnumber"
        ng-change="addShiftNumber(event.shiftnumber)"
        ng-options="timeslot.value as timeslot.name for timeslot in shiftnumbers"
        ng-init="event.shiftnumber = shiftnumbers[0].value"
        class="btn">
</select>
<div ng-repeat="shiftnumber in selectedShiftnumbers">
  {{shiftnumber}}
</div>

Script

$scope.addShiftNumber = function(num){
  $scope.selectedShiftnumbers = [];
  for(var i=0; i< num; i++) {
    $scope.selectedShiftnumbers.push(i);
  }
}

DEMO

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