在AngularJS中的选项选择上动态创建div

时间:2014-08-27 09:22:07

标签: javascript jquery html css angularjs

我正在尝试使用选项选择值动态创建div,但ng-repeat无效。让我知道我在这里做错了什么。

以下是我的HTML代码 -

<!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>

以下是我的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

1 个答案:

答案 0 :(得分:1)

创建一个新数组 selectedShiftnumbers 以存储选定的值。然后使用 ngRepeat 列出它。

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>

脚本

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

DEMO