angularjs - select2 and two way binding
by Tessy Thomas
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.0/select2.min.js"></script>
<script src="https://rawgithub.com/angular-ui/ui-select2/master/src/select2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.1/bootstrap.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.0/select2.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.1/css/bootstrap.css">
<div ng-controller="MyCtrl">
<!-- this list is for assure, that two way binding works -->
List of Tags:
<ul>
<li data-ng-repeat="tag in post.tags">{{tag.tag}}</li>
</ul>
<br>
Select Tags: <!-- selected items are not binded to the model -->
<select multiple ui-select2 class="form-control" data-ng-model="selectedTags" >
<option data-ng-repeat="tag in post.tags" value="{{tag._id}}" text="">{{tag.tag}}</option>
</select>
<button ng-click="addMoreTags()">
Add More Tags
</button>
</div>
JavaScript
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.selectedTags = [4]; // Averell is preselected (id:4)
$scope.post = {
tags: [
{tag: "Angular JS", _id: "5ae410756b7a61080cd17c81"},
{tag: "Java", _id: "5ae410756b7a61080cd17c80"},
{tag: "JQuery", _id: "5ae410756b7a61080cd17c7f"}
]
};
$scope.addMoreTags = function(){
var newTags = [
{tag: "React JS", _id: "5ae410756b754cd17c82"},
{tag: "Vuejs", _id: "5ae410756b45480cd17c83"}
];
$scope.post.tags = $scope.post.tags.concat(newTags);
};
};