making angularjs bootstrap multi select work - angularjs

i just happened to stumble upon this amazing multi-select textbox provided on the following link:
http://angularscript.com/bootstrap-multiple-select-angularjs/
i downloaded the zip and tried to run it on my local server.
the links were missing so i linked it to bootstrap and angular.js. But i was unsuccessful.can anyone try it out and see whats missing.
src/multiselect.html:
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.2/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.2/ui-bootstrap-tpls.min.js"></script>
<script src="./multiselect.js"></script>
<script src="./dist/angular-bootstrap-multiselect.js"></script>
<script src="./dist/angular-bootstrap-multiselect.min.js"></script>
<script src="./dist/angular-bootstrap-multiselect-templates.js"></script>
</head>
<body>
<div class="btn-group" style="width: 100%">
<button type="button" class="form-control btn btn-default btn-block dropdown-toggle" ng-click="toggleDropdown()" ng-disabled="disabled">
{{getButtonText()}} <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-form"
ng-style="{display: open ? 'block' : 'none'}" style="width: 100%; overflow-x: auto">
<li ng-show="showSelectAll">
<a ng-click="selectAll()" href="">
<span class="glyphicon glyphicon-ok"></span> Select All
</a>
</li>
<li ng-show="showUnselectAll">
<a ng-click="unselectAll()" href="">
<span class="glyphicon glyphicon-remove"></span> Unselect All
</a>
</li>
<li ng-show="(showSelectAll || showUnselectAll)"
class="divider">
</li>
<li role="presentation" ng-repeat="option in selectedOptions" class="active">
<a class="item-selected" href="" ng-click="toggleItem(option); $event.stopPropagation()">
<span class="glyphicon glyphicon-remove"></span>
{{getDisplay(option)}}
</a>
</li>
<li ng-show="selectedOptions.length > 0" class="divider"></li>
<li ng-show="showSearch">
<div class="dropdown-header">
<input type="text" class="form-control input-sm" style="width: 100%;"
ng-model="searchFilter" placeholder="Search..." ng-change="updateOptions()"/>
</div>
</li>
<li ng-show="showSearch" class="divider"></li>
<li role="presentation" ng-repeat="option in unselectedOptions | filter:search() | limitTo: searchLimit"
ng-if="!isSelected(option)"
ng-class="{disabled : selectionLimit && selectedOptions.length >= selectionLimit}">
<a class="item-unselected" href="" ng-click="toggleItem(option); $event.stopPropagation()">
{{getDisplay(option)}}
</a>
</li>
<li class="divider" ng-show="selectionLimit > 1"></li>
<li role="presentation" ng-show="selectionLimit > 1">
<a>{{selectedOptions.length || 0}} / {{selectionLimit}} selected</a>
</li>
</ul>
</div>
</body>
</html>
src/multiselect.js:
(function () {
'use strict';
var multiselect = angular.module('btorfs.multiselect', ['btorfs.multiselect.templates']);
multiselect.getRecursiveProperty = function (object, path) {
return path.split('.').reduce(function (object, x) {
if (object) {
return object[x];
} else {
return null;
}
}, object)
};
multiselect.directive('multiselect', function ($filter, $document, $log) {
return {
restrict: 'AE',
scope: {
options: '=',
displayProp: '#',
idProp: '#',
searchLimit: '=?',
selectionLimit: '=?',
showSelectAll: '=?',
showUnselectAll: '=?',
showSearch: '=?',
searchFilter: '=?',
disabled: '=?ngDisabled',
defaultText: '#'
},
require: 'ngModel',
templateUrl: 'multiselect.html',
link: function ($scope, $element, $attrs, $ngModelCtrl) {
$scope.selectionLimit = $scope.selectionLimit || 0;
$scope.searchLimit = $scope.searchLimit || 25;
$scope.defaultText = $scope.defaultText || 'Select';
$scope.searchFilter = '';
$scope.resolvedOptions = [];
if (typeof $scope.options !== 'function') {
$scope.resolvedOptions = $scope.options;
}
if (typeof $attrs.disabled != 'undefined') {
$scope.disabled = true;
}
$scope.toggleDropdown = function () {
$scope.open = !$scope.open;
};
var closeHandler = function (event) {
if (!$element[0].contains(event.target)) {
$scope.$apply(function () {
$scope.open = false;
});
}
};
$document.on('click', closeHandler);
var updateSelectionLists = function () {
if (!$ngModelCtrl.$viewValue) {
if ($scope.selectedOptions) {
$scope.selectedOptions = [];
}
$scope.unselectedOptions = $scope.resolvedOptions.slice(); // Take a copy
} else {
$scope.selectedOptions = $scope.resolvedOptions.filter(function (el) {
var id = $scope.getId(el);
for (var i = 0; i < $ngModelCtrl.$viewValue.length; i++) {
var selectedId = $scope.getId($ngModelCtrl.$viewValue[i]);
if (id === selectedId) {
return true;
}
}
return false;
});
$scope.unselectedOptions = $scope.resolvedOptions.filter(function (el) {
return $scope.selectedOptions.indexOf(el) < 0;
});
}
};
$ngModelCtrl.$render = function () {
updateSelectionLists();
};
$ngModelCtrl.$viewChangeListeners.push(function () {
updateSelectionLists();
});
$ngModelCtrl.$isEmpty = function (value) {
if (value) {
return (value.length === 0);
} else {
return true;
}
};
var watcher = $scope.$watch('selectedOptions', function () {
$ngModelCtrl.$setViewValue(angular.copy($scope.selectedOptions));
}, true);
$scope.$on('$destroy', function () {
$document.off('click', closeHandler);
if (watcher) {
watcher(); // Clean watcher
}
});
$scope.getButtonText = function () {
if ($scope.selectedOptions && $scope.selectedOptions.length === 1) {
return $scope.getDisplay($scope.selectedOptions[0]);
}
if ($scope.selectedOptions && $scope.selectedOptions.length > 1) {
var totalSelected;
totalSelected = angular.isDefined($scope.selectedOptions) ? $scope.selectedOptions.length : 0;
if (totalSelected === 0) {
return $scope.defaultText;
} else {
return totalSelected + ' ' + 'selected';
}
} else {
return $scope.defaultText;
}
};
$scope.selectAll = function () {
$scope.selectedOptions = $scope.resolvedOptions;
$scope.unselectedOptions = [];
};
$scope.unselectAll = function () {
$scope.selectedOptions = [];
$scope.unselectedOptions = $scope.resolvedOptions;
};
$scope.toggleItem = function (item) {
if (typeof $scope.selectedOptions === 'undefined') {
$scope.selectedOptions = [];
}
var selectedIndex = $scope.selectedOptions.indexOf(item);
var currentlySelected = (selectedIndex !== -1);
if (currentlySelected) {
$scope.unselectedOptions.push($scope.selectedOptions[selectedIndex]);
$scope.selectedOptions.splice(selectedIndex, 1);
} else if (!currentlySelected && ($scope.selectionLimit === 0 || $scope.selectedOptions.length < $scope.selectionLimit)) {
var unselectedIndex = $scope.unselectedOptions.indexOf(item);
$scope.unselectedOptions.splice(unselectedIndex, 1);
$scope.selectedOptions.push(item);
}
};
$scope.getId = function (item) {
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.idProp) {
return multiselect.getRecursiveProperty(item, $scope.idProp);
} else {
$log.error('Multiselect: when using objects as model, a idProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.getDisplay = function (item) {
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.displayProp) {
return multiselect.getRecursiveProperty(item, $scope.displayProp);
} else {
$log.error('Multiselect: when using objects as model, a displayProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.isSelected = function (item) {
if (!$scope.selectedOptions) {
return false;
}
var itemId = $scope.getId(item);
for (var i = 0; i < $scope.selectedOptions.length; i++) {
var selectedElement = $scope.selectedOptions[i];
if ($scope.getId(selectedElement) === itemId) {
return true;
}
}
return false;
};
$scope.updateOptions = function () {
if (typeof $scope.options === 'function') {
$scope.options().then(function (resolvedOptions) {
$scope.resolvedOptions = resolvedOptions;
updateSelectionLists();
});
}
};
// This search function is optimized to take into account the search limit.
// Using angular limitTo filter is not efficient for big lists, because it still runs the search for
// all elements, even if the limit is reached
$scope.search = function () {
var counter = 0;
return function (item) {
if (counter > $scope.searchLimit) {
return false;
}
var displayName = $scope.getDisplay(item);
if (displayName) {
var result = displayName.toLowerCase().indexOf($scope.searchFilter.toLowerCase()) > -1;
if (result) {
counter++;
}
return result;
}
}
};
}
};
});
}());

Try to add to your <Body> the ng-app="MyApp" and to your <div> the ng-controller="MyControllerApp".
The result will be
<body ng-app="MyApp">
<div ng-controller="MyControllerApp">

Related

How to Create playlist in angularjs audio app?

I had created a angular audio app. i want to display play list in it . Using directive to trigger play pause and other operations. Please help me to create play list here.
my main html is
<!DOCTYPE html>
<html ng-app="app">
<head>
<title> AUDIO</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="css/ng-cool-audio.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="js/ng-cool-audio.js"></script>
<script src="js/app.js"></script>
<style>
body {
background-color: #f5f5f5;
font-family: Helvetica Neue, Helvetica, arial, sans-serif;
}
.main {
width: 800px;
margin: 100px auto;
}
</style>
</head>
<body ng-controller="MainCtrl">
<div class="main">
<ng-cool-audio source="source2"></ng-cool-audio>
</div>
</body>
</html>
my html template is
<div class="ng-cool-audio-container">
<audio>
Your browser seems to be upgraded! :)
</audio>
<div class="ng-cool-audio-preview">
<div class="ncv-audio-left">
<div class="ncv-img-container">
<img ng-src="{{audio.cover}}" alt="Photo">
</div>
</div>
<div class="ncv-audio-right">
<div class="ncv-audio-right-top">
<div class="ncv-header">
<div class="ncv-header-title">{{audio.author}}</div>
<div class="ncv-header-subtitle">{{audio.name}}</div>
<div class="ncv-audio-sound">
<i class="fa fa-volume-up" ng-show="!isMuted" ng-click="volumeOff()"></i>
<i class="fa fa-volume-off" ng-show="isMuted" ng-click="volumeOn()"></i>
<input type="range" max="10" min="0" value="5">
</div>
</div>
</div>
<div class="ncv-audio-right-bottom">
<div class="ncv-audio-controls">
<i class="fa fa-backward" ng-click="playBackward()"></i>
<i class="fa fa-play" ng-click="play()"></i>
<i class="fa fa-pause" ng-click="pause()"></i>
<i class="fa fa-forward" ng-click="playForward()"></i>
</div>
<div class="ncv-progress">
<progress class="ncv-progress-bar" max="100" value="{{progressValue}}"></progress>
</div>
<div class="ncv-time">
<span class="ncv-current-time">{{currentTime}}</span>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
<h4> PLAY LIST </h4>
<div class="col-lg-3" ng-repeat="song in source2">
{{song.audio.name}}
</div>
</div>
</div>
app.js is
(function() {
'use strict';
angular
.module('app', [
'ngCoolAudio'
])
.controller('MainCtrl', function($scope) {
$scope.source2 = {
audio: [{
author: 'Dr. SPB',
cover: 'images/about.jpg',
src: 'audio/AADI ANAADI-SPB.mp3',
name: 'AADI ANAADI'
},
{
author: 'Dr.RAJ',
cover: 'images/about.jpg',
src: 'audio/BHAVA SAAGARADA AALADI-DR.RAJ.mp3',
name: 'BHAVA SAAGARADA AALADI'
},
{
author: 'Dr.RAJ',
cover: 'images/about.jpg',
src: 'audio/CHARAKULAAMBUDHI CHANDIRA-DR.RAJ (2).mp3',
name: 'CHARAKULAAMBUDHI CHANDIRA'
},
{
author: 'S.JANAKI',
cover: 'images/about.jpg',
src: 'audio/DHYANA MAADUTHIRU-S.JANAKI .mp3',
name: 'DHYANA MAADUTHIRU'
},
{
author: 'OM',
cover: 'images/about.jpg',
src: 'audio/Om Namahshivaya.mp3',
name: 'OM NAMAHSHIVAYA'
}
],
config: {
autoplay: false,
loop: true
}
}
})
})();
audio directive is
(function() {
'use strict';
angular
.module('ngCoolAudio', [])
.directive('ngCoolAudio', [
'$timeout',
'$sce',
function($timeout, $sce) {
return {
restrict: 'AE',
scope: {
source: '=source'
},
replace: true,
templateUrl: 'html/audio.html',
controller: ['$scope', '$element', function($scope, $element) {
//check source file
if (!$scope.source || !$scope.source.audio) {
throw new Error('Source seems not to config right!');
return;
}
var container = $element[0].querySelector('.ng-cool-audio-container');
var audio = $element[0].querySelector('audio');
var volume_range = $element[0].querySelector('.ncv-audio-sound input[type="range"]');
var $audio = angular.element(audio);
$scope.audio = {};
//private method
var calCulateTime = function() {
var secs = parseInt(audio.currentTime % 60);
var mins = parseInt((audio.currentTime / 60) % 60);
// Ensure it's two digits. For example, 03 rather than 3.
secs = ("0" + secs).slice(-2);
mins = ("0" + mins).slice(-2);
return mins + ':' + secs;
}
var calCulateProgress = function() {
var percent = (100 / audio.duration) * audio.currentTime;
return percent;
}
var generateAudio = function(audio) {
if (!audio.src) {
throw new Error('Not found src in your audio config');
return;
}
$audio.attr('src', audio.src);
$scope.audio.cover = audio.cover || 'http://7xj610.com1.z0.glb.clouddn.com/29ce98b4349b72c2778d2f82823159b06f98f8bc.jpeg';
$scope.audio.author = audio.author || 'Unknow';
$scope.audio.name = audio.name || 'Unknow';
}
$scope.currentTrack = 0;
$scope.jumpInterval = 10;
$scope.init = function() {
$scope.currentTime = '00:00';
$scope.progressValue = 0;
$scope.isPlaying = false;
$scope.isMuted = false;
$scope.setInterface($scope.currentTrack);
$scope.addEvents();
};
$scope.setInterface = function(index) {
var isArray = angular.isArray($scope.source.audio);
if (isArray) {
$scope.audioCollection = $scope.source.audio;
generateAudio($scope.audioCollection[index]);
} else {
generateAudio($scope.source.audio);
}
if ($scope.source.config) {
if ($scope.source.config.autoplay) {
$audio.attr('autoplay', 'autoplay');
$scope.play();
}
if ($scope.source.config.loop) {
$audio.attr('loop', 'loop');
}
}
};
//toggle play pause
$scope.play = function() {
audio.play();
$scope.isPlaying = true;
};
$scope.pause = function() {
audio.pause();
$scope.isPlaying = false;
};
//toggle mute
$scope.volumeOn = function() {
audio.muted = false;
$scope.isMuted = false;
};
$scope.volumeOff = function() {
audio.muted = true;
$scope.isMuted = true;
};
//backward forward
$scope.playBackward = function() {
//here jump to pre song
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.currentTrack -= 1;
if ($scope.currentTrack < 0) {
$scope.currentTrack = $scope.audioCollection.length - 1;
}
$scope.init();
$scope.play();
} else {
var toTime = audio.currentTime - $scope.jumpInterval;
if (toTime < 0) {
audio.currentTime = 0;
} else {
audio.currentTime = toTime;
}
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
};
$scope.playForward = function() {
//here jump to next song
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.currentTrack += 1;
if ($scope.currentTrack > $scope.audioCollection.length - 1) {
$scope.currentTrack = 0;
}
$scope.init();
$scope.play();
} else {
var toTime = audio.currentTime + $scope.jumpInterval;
if (toTime > audio.duration) {
audio.currentTime = audio.duration;
} else {
audio.currentTime = toTime;
}
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
};
//skip progress
$scope.skipProgress = function(e) {
//update time and progress
var target = e.target;
var offsetX = 0;
if (!e.pageX || !target.offsetLeft) {
offsetX = e.offsetX ? e.offsetX : e.layerX;
} else {
offsetX = e.pageX - target.offsetLeft;
}
var pos = offsetX / target.offsetWidth;
audio.currentTime = pos * audio.duration;
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
}
$scope.addEvents = function() {
//time update
// progress update
audio.addEventListener('timeupdate', function() {
$scope.currentTime = calCulateTime();
$scope.progressValue = calCulateProgress();
$scope.$apply();
}, false);
audio.addEventListener('ended', function() {
//auto play next
if ($scope.audioCollection && $scope.audioCollection.length > 0) {
$scope.playForward();
}
});
//angular seems dont support input[range] stuff so let's do it event
volume_range.addEventListener('change', function() {
audio.volume = parseFloat(this.value / 10);
}, false);
}
}],
link: function(scope, ele, attrs) {
scope.init();
}
}
}
])
})();

How to call controller method from custom directive in AngularJs

UI
<div class="row" ng-app="myModule" ng-controller="multiselect">
<div class="col-md-2">
<div id="lob" ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="lobs" attrfilterprojectsonlob="getProjects"
selected-model="lobsSelected" checkboxes="true">
</div>
</div>
<div class="col-md-2">
<div id="projects" ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="projects"
selected-model="projectsSelected" checkboxes="true">
</div>
</div>
</div>
Angular Controller
var myApp = angular.module('myModule', ['angularjs-dropdown-multiselect']);
myApp.controller('multiselect', ['$scope', '$http', function ($scope, $http) {
$scope.lobsSelected = [];
$scope.lobs = [];
$scope.projectsSelected = [];
$scope.projects = [];
$scope.dropdownSetting = {
scrollable: true,
scrollableHeight: '200px'
}
$http.get('Home/GetALLLOB').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.lobs.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
$http.get('Home/GetAllProjects').then(function (data) {
debugger;
angular.forEach(data.data, function (value, index) {
$scope.projects.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
$scope.getProjects = function (selectedId) {
debugger;
var parentId = id;
$http.get('Home/GetAllProjects', { params: { "parentId": selectedId } })
.then(function (data) {
angular.forEach(data.data, function (value, index) {
debugger;
$scope.projects.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
.catch(function (data) {
console.error('Gists error', data.status, data.data);
})
}
}])
Directive : - Please ignore fn_template()
'use strict';
var directiveModule = angular.module('angularjs-dropdown-multiselect', []);
directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
function ($filter, $document, $compile, $parse) {
return {
//restrict: 'AE',
restrict: 'AEC',
scope: {
selectedModel: '=',
options: '=',
extraSettings: '=',
events: '=',
searchFilter: '=?',
translationTexts: '=',
groupBy: '#',
fn_selectAll: '&',
selectedId :'=',
attrfilterProjectsonLob: '&'
},
template: fn_Template,
link: function ($scope, $element, $attrs) {
var $dropdownTrigger = $element.children()[0];
$scope.toggleDropdown = function () {
$scope.open = !$scope.open;
};
$scope.checkboxClick = function ($event, id) {
$scope.setSelectedItem(id);
$event.stopImmediatePropagation();
};
$scope.filterProjectsonLob = function ($event, id) {
debugger;
$scope.selectedId = id;
$scope.attrfilterProjectsonLob({value : selectedId});
}
$scope.externalEvents = {
onItemSelect: angular.noop,
onItemDeselect: angular.noop,
onSelectAll: angular.noop,
onDeselectAll: angular.noop,
onInitDone: angular.noop,
onMaxSelectionReached: angular.noop
};
$scope.settings = {
dynamicTitle: true,
scrollable: false,
scrollableHeight: '300px',
closeOnBlur: true,
displayProp: 'label',
idProp: 'id',
externalIdProp: 'id',
enableSearch: false,
selectionLimit: 0,
showCheckAll: true,
showUncheckAll: true,
closeOnSelect: false,
buttonClasses: 'btn btn-default',
closeOnDeselect: false,
groupBy: $attrs.groupBy || undefined,
groupByTextProvider: null,
smartButtonMaxItems: 0,
smartButtonTextConverter: angular.noop
};
$scope.texts = {
checkAll: 'Check All',
uncheckAll: 'Uncheck All',
selectionCount: 'checked',
selectionOf: '/',
searchPlaceholder: 'Search...',
buttonDefaultText: 'LOB',
dynamicButtonTextSuffix: 'Selected',
LOBSelected: ''
};
$scope.searchFilter = $scope.searchFilter || '';
if (angular.isDefined($scope.settings.groupBy)) {
$scope.$watch('options', function (newValue) {
if (angular.isDefined(newValue)) {
$scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
}
});
}
angular.extend($scope.settings, $scope.extraSettings || []);
angular.extend($scope.externalEvents, $scope.events || []);
angular.extend($scope.texts, $scope.translationTexts);
$scope.singleSelection = $scope.settings.selectionLimit === 1;
function getFindObj(id) {
var findObj = {};
if ($scope.settings.externalIdProp === '') {
findObj[$scope.settings.idProp] = id;
} else {
findObj[$scope.settings.externalIdProp] = id;
}
return findObj;
}
function clearObject(object) {
for (var prop in object) {
delete object[prop];
}
}
if ($scope.singleSelection) {
if (angular.isArray($scope.selectedModel) && $scope.selectedModel.length === 0) {
clearObject($scope.selectedModel);
}
}
if ($scope.settings.closeOnBlur) {
$document.on('click', function (e) {
var target = e.target.parentElement;
var parentFound = false;
while (angular.isDefined(target) && target !== null && !parentFound) {
if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
if (target === $dropdownTrigger) {
parentFound = true;
}
}
target = target.parentElement;
}
if (!parentFound) {
$scope.$apply(function () {
$scope.open = false;
});
}
});
}
$scope.getGroupTitle = function (groupValue) {
if ($scope.settings.groupByTextProvider !== null) {
return $scope.settings.groupByTextProvider(groupValue);
}
return groupValue;
};
$scope.getButtonText = function () {
if ($scope.settings.dynamicTitle && ($scope.selectedModel.length > 0 || (angular.isObject($scope.selectedModel) && _.keys($scope.selectedModel).length > 0))) {
//if ($scope.settings.smartButtonMaxItems > 0) {
if ($scope.settings.smartButtonMaxItems >= 0) {
var itemsText = [];
var SelectedTexts = [];
angular.forEach($scope.options, function (optionItem) {
if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);
$scope.SelectedTexts = displayText;
var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);
itemsText.push(converterResponse ? converterResponse : displayText);
}
});
//if ($scope.selectedModel.length > $scope.settings.smartButtonMaxItems) {
// itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
// itemsText.push('...');
//}
if (itemsText.length <= 2) {
return itemsText.join(', ');
}
else {
var totalSelected;
if ($scope.singleSelection) {
totalSelected = ($scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
} else {
totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
}
if (totalSelected === 0) {
return $scope.texts.buttonDefaultText;
} else {
return totalSelected + ' ' + $scope.texts.buttonDefaultText + ' ' + $scope.texts.dynamicButtonTextSuffix;
}
}
}
} else {
return $scope.texts.buttonDefaultText;
}
};
$scope.getPropertyForObject = function (object, property) {
if (angular.isDefined(object) && object.hasOwnProperty(property)) {
return object[property];
}
return '';
};
$scope.selectAll = function () {
$scope.deselectAll(false);
$scope.externalEvents.onSelectAll();
angular.forEach($scope.options, function (value) {
$scope.setSelectedItem(value[$scope.settings.idProp], true);
});
};
$scope.deselectAll = function (sendEvent) {
sendEvent = sendEvent || true;
if (sendEvent) {
$scope.externalEvents.onDeselectAll();
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
} else {
$scope.selectedModel.splice(0, $scope.selectedModel.length);
}
};
$scope.setSelectedItem = function (id, dontRemove) {
debugger;
var findObj = getFindObj(id);
var finalObj = null;
if ($scope.settings.externalIdProp === '') {
finalObj = _.find($scope.options, findObj);
} else {
finalObj = findObj;
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
angular.extend($scope.selectedModel, finalObj);
$scope.externalEvents.onItemSelect(finalObj);
if ($scope.settings.closeOnSelect) $scope.open = false;
return;
}
dontRemove = dontRemove || false;
var exists = _.findIndex($scope.selectedModel, findObj) !== -1;
if (!dontRemove && exists) {
$scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
$scope.externalEvents.onItemDeselect(findObj);
} else if (!exists && ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length < $scope.settings.selectionLimit)) {
$scope.selectedModel.push(finalObj);
$scope.externalEvents.onItemSelect(finalObj);
}
if ($scope.settings.closeOnSelect) $scope.open = false;
};
$scope.isChecked = function (id) {
if ($scope.singleSelection) {
return $scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp]) && $scope.selectedModel[$scope.settings.idProp] === getFindObj(id)[$scope.settings.idProp];
}
return _.findIndex($scope.selectedModel, getFindObj(id)) !== -1;
};
$scope.externalEvents.onInitDone();
}
};
}]);
function fn_Template(element, attrs) {
var checkboxes = attrs.checkboxes ? true : false;
var groups = attrs.groupBy ? true : false;
var template = '<div class="multiselect-parent btn-group dropdown-multiselect">';
template += '<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} <span class="caret"></span></button>';
template += '<ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" >';
template += '<li ng-hide="!settings.showCheckAll || settings.selectionLimit > 0"><a data-ng-click="selectAll()"><span class="glyphicon glyphicon-ok"></span> {{texts.checkAll}}</a>';
template += '<li ng-show="settings.showUncheckAll"><a data-ng-click="deselectAll();"><span class="glyphicon glyphicon-remove"></span> {{texts.uncheckAll}}</a></li>';
template += '<li ng-hide="(!settings.showCheckAll || settings.selectionLimit > 0) && !settings.showUncheckAll" class="divider"></li>';
template += '<li ng-show="settings.enableSearch"><div class="dropdown-header"><input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /></li>';
template += '<li ng-show="settings.enableSearch" class="divider"></li>';
if (groups) {
template += '<li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header">{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}</li>';
template += '<li ng-repeat-end role="presentation">';
} else {
template += '<li role="presentation" ng-repeat="option in options | filter: searchFilter">';
}
template += '<a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))">';
if (checkboxes) {
template += '<div class="checkbox"><label><input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp)); filterProjectsonLob($event, getPropertyForObject(option,settings.idProp)) "ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}</label></div></a>';
} else {
template += '<span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"></span> {{getPropertyForObject(option, settings.displayProp)}}</a>';
}
template += '</li>';
template += '<li class="divider" ng-show="settings.selectionLimit > 1"></li>';
template += '<li role="presentation" ng-show="settings.selectionLimit > 1"><a role="menuitem">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}</a></li>';
template += '</ul>';
template += '</div>';
element.html(template);
}
Comments
---------- .
Please guide me what is wrong i am doing, as controllers method is not getting invoked.
I need to call $scope.getProjects method present in controller from $scope.filterProjectsonLob in directive. Please guide me as i am new to angularJs.
Your directive can have it's own controller:
angular.directive(function() { //blah blah
return {
//restrict: 'AE',
restrict: 'AEC',
scope: {
},
controller: multiselect,
controllerAs: 'vm'
}
});
Then it's a matter of vm.methodNameCall(arguments) as you would normally do.
What's happening here is that your controller is existing on the parent scope of your directive and the directive has an isolate scope so it doesn't see its parent scope's data.
The simplest solution (but not necessarily most correct) is to use $scope.$parent ($scope.$parent.getProjects) from inside your directive to access the controller's scope.
A more correct solution is to refactor your multiselect controller to be a directive. With multiselect as a directive (ex. ngMultiselect), you would be able to inject its controller into other directives. You won't need to change your controller code that much, just make a directive with it as a controller rather than use ng-controller.
Step 1: replace ng-controller with ngMultiselect directive.
directiveModule.directive('ngMultiselect', function(){
return {
restrict: 'AEC',
controller: 'multiselect'
};
});
<div class="row" ng-app="myModule" ng-multiselect> ... </div>
Step 2: update multiselect controller to expose getProjects function
// change:
$scope.getProjects = function (selectedId) {...};
// to:
this.getProjects = function (selectedId) {...};
// and if you still need getProjects on multiselect's scope, you can add $scope.getProjects = this.getProjects;
Step 3: Inject controller into ngDropdownMultiselect by requiring ngMultiselect
directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
function ($filter, $document, $compile, $parse) {
return {
//restrict: 'AE',
restrict: 'AEC',
require: 'ngMultiselect',
scope: {
selectedModel: '=',
options: '=',
// etc ...
},
template: fn_Template,
link: function ($scope, $element, $attrs, MultiselectCtrl) {
$scope.getProjects = MultiselectCtrl.getProjects;
// and the rest of your stuff here...
}
};
}
]);
Learning how to set up and differentiate controllers + directive link functions is certainly one of the finer points of learning angular. I would say it is necessary for building anything beyond simple components. There are lots of tutorials about it, but it can be tricky to really grok until you come across it in your own codings.
Edit:
Just wanted to note that you will need to take a look at which modules you are defining your directives and controller in and set your module dependencies accordingly.

Dynamically creating multiselect Dropdown in AngularJs

Hi i have one multiselect dropdown in angular which invokes directive. I want to create 5 dropdown which will refer same directive and controller, but for each dropdown there will be different action method in MVC. Your help can save my life
Controller
var myApp = angular.module('myModule', ['angularjs-dropdown-multiselect']);
myApp.controller('multiselect', ['$scope', '$http', function ($scope, $http) {
$scope.lobsSelected = [];
$scope.lobs = [];
$scope.dropdownSetting = {
scrollable: true,
scrollableHeight: '200px'
}
$http.get('Home/GetALLLOB').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.lobs.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
}])
Directive
'use strict';
var directiveModule = angular.module('angularjs-dropdown-multiselect', []);
directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
function ($filter, $document, $compile, $parse) {
return {
//restrict: 'AE',
restrict: 'AEC',
scope: {
selectedModel: '=',
options: '=',
extraSettings: '=',
events: '=',
searchFilter: '=?',
translationTexts: '=',
groupBy: '#',
fn_selectAll: '&',
},
template: fn_Template,
link: function ($scope, $element, $attrs) {
var $dropdownTrigger = $element.children()[0];
$scope.toggleDropdown = function () {
$scope.open = !$scope.open;
};
$scope.checkboxClick = function ($event, id) {
$scope.setSelectedItem(id);
//var obj = getPropertyForObject(option, settings.idProp);
$event.stopImmediatePropagation();
};
$scope.externalEvents = {
onItemSelect: angular.noop,
onItemDeselect: angular.noop,
onSelectAll: angular.noop,
onDeselectAll: angular.noop,
onInitDone: angular.noop,
onMaxSelectionReached: angular.noop
};
$scope.settings = {
dynamicTitle: true,
scrollable: false,
scrollableHeight: '300px',
closeOnBlur: true,
displayProp: 'label',
idProp: 'id',
externalIdProp: 'id',
enableSearch: false,
selectionLimit: 0,
showCheckAll: true,
showUncheckAll: true,
closeOnSelect: false,
buttonClasses: 'btn btn-default',
closeOnDeselect: false,
groupBy: $attrs.groupBy || undefined,
groupByTextProvider: null,
smartButtonMaxItems: 0,
smartButtonTextConverter: angular.noop
};
$scope.texts = {
checkAll: 'Check All',
uncheckAll: 'Uncheck All',
selectionCount: 'checked',
selectionOf: '/',
searchPlaceholder: 'Search...',
buttonDefaultText: 'LOB',
dynamicButtonTextSuffix: 'Selected',
LOBSelected: ''
};
$scope.searchFilter = $scope.searchFilter || '';
if (angular.isDefined($scope.settings.groupBy)) {
$scope.$watch('options', function (newValue) {
if (angular.isDefined(newValue)) {
$scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
}
});
}
angular.extend($scope.settings, $scope.extraSettings || []);
angular.extend($scope.externalEvents, $scope.events || []);
angular.extend($scope.texts, $scope.translationTexts);
$scope.singleSelection = $scope.settings.selectionLimit === 1;
function getFindObj(id) {
var findObj = {};
if ($scope.settings.externalIdProp === '') {
findObj[$scope.settings.idProp] = id;
} else {
findObj[$scope.settings.externalIdProp] = id;
}
return findObj;
}
function clearObject(object) {
for (var prop in object) {
delete object[prop];
}
}
if ($scope.singleSelection) {
if (angular.isArray($scope.selectedModel) && $scope.selectedModel.length === 0) {
clearObject($scope.selectedModel);
}
}
if ($scope.settings.closeOnBlur) {
$document.on('click', function (e) {
var target = e.target.parentElement;
var parentFound = false;
while (angular.isDefined(target) && target !== null && !parentFound) {
if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
if (target === $dropdownTrigger) {
parentFound = true;
}
}
target = target.parentElement;
}
if (!parentFound) {
$scope.$apply(function () {
$scope.open = false;
});
}
});
}
$scope.getGroupTitle = function (groupValue) {
if ($scope.settings.groupByTextProvider !== null) {
return $scope.settings.groupByTextProvider(groupValue);
}
return groupValue;
};
$scope.getButtonText = function () {
if ($scope.settings.dynamicTitle && ($scope.selectedModel.length > 0 || (angular.isObject($scope.selectedModel) && _.keys($scope.selectedModel).length > 0))) {
//if ($scope.settings.smartButtonMaxItems > 0) {
if ($scope.settings.smartButtonMaxItems >= 0) {
var itemsText = [];
var SelectedTexts = [];
angular.forEach($scope.options, function (optionItem) {
if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);
$scope.SelectedTexts = displayText;
var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);
itemsText.push(converterResponse ? converterResponse : displayText);
}
});
//if ($scope.selectedModel.length > $scope.settings.smartButtonMaxItems) {
// itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
// itemsText.push('...');
//}
if (itemsText.length <= 2) {
return itemsText.join(', ');
}
else {
var totalSelected;
if ($scope.singleSelection) {
totalSelected = ($scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
} else {
totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
}
if (totalSelected === 0) {
return $scope.texts.buttonDefaultText;
} else {
return totalSelected + ' ' + $scope.texts.buttonDefaultText + ' ' + $scope.texts.dynamicButtonTextSuffix;
}
}
}
} else {
return $scope.texts.buttonDefaultText;
}
};
$scope.getPropertyForObject = function (object, property) {
if (angular.isDefined(object) && object.hasOwnProperty(property)) {
return object[property];
}
return '';
};
$scope.selectAll = function () {
debugger;
$scope.deselectAll(false);
$scope.externalEvents.onSelectAll();
angular.forEach($scope.options, function (value) {
$scope.setSelectedItem(value[$scope.settings.idProp], true);
});
};
$scope.deselectAll = function (sendEvent) {
sendEvent = sendEvent || true;
if (sendEvent) {
$scope.externalEvents.onDeselectAll();
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
} else {
$scope.selectedModel.splice(0, $scope.selectedModel.length);
}
};
$scope.setSelectedItem = function (id, dontRemove) {
var findObj = getFindObj(id);
var finalObj = null;
if ($scope.settings.externalIdProp === '') {
finalObj = _.find($scope.options, findObj);
} else {
finalObj = findObj;
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
angular.extend($scope.selectedModel, finalObj);
$scope.externalEvents.onItemSelect(finalObj);
if ($scope.settings.closeOnSelect) $scope.open = false;
return;
}
dontRemove = dontRemove || false;
var exists = _.findIndex($scope.selectedModel, findObj) !== -1;
if (!dontRemove && exists) {
$scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
$scope.externalEvents.onItemDeselect(findObj);
} else if (!exists && ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length < $scope.settings.selectionLimit)) {
$scope.selectedModel.push(finalObj);
$scope.externalEvents.onItemSelect(finalObj);
}
if ($scope.settings.closeOnSelect) $scope.open = false;
};
$scope.isChecked = function (id) {
if ($scope.singleSelection) {
return $scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp]) && $scope.selectedModel[$scope.settings.idProp] === getFindObj(id)[$scope.settings.idProp];
}
return _.findIndex($scope.selectedModel, getFindObj(id)) !== -1;
};
$scope.externalEvents.onInitDone();
}
};
}]);
function fn_Template(element, attrs) {
var checkboxes = attrs.checkboxes ? true : false;
var groups = attrs.groupBy ? true : false;
var template = '<div class="multiselect-parent btn-group dropdown-multiselect">';
template += '<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} <span class="caret"></span></button>';
template += '<ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" >';
template += '<li ng-hide="!settings.showCheckAll || settings.selectionLimit > 0"><a data-ng-click="selectAll()"><span class="glyphicon glyphicon-ok"></span> {{texts.checkAll}}</a>';
template += '<li ng-show="settings.showUncheckAll"><a data-ng-click="deselectAll();"><span class="glyphicon glyphicon-remove"></span> {{texts.uncheckAll}}</a></li>';
template += '<li ng-hide="(!settings.showCheckAll || settings.selectionLimit > 0) && !settings.showUncheckAll" class="divider"></li>';
template += '<li ng-show="settings.enableSearch"><div class="dropdown-header"><input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /></li>';
template += '<li ng-show="settings.enableSearch" class="divider"></li>';
if (groups) {
template += '<li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header">{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}</li>';
template += '<li ng-repeat-end role="presentation">';
} else {
template += '<li role="presentation" ng-repeat="option in options | filter: searchFilter">';
}
template += '<a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))">';
if (checkboxes) {
template += '<div class="checkbox"><label><input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}</label></div></a>';
} else {
template += '<span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"></span> {{getPropertyForObject(option, settings.displayProp)}}</a>';
}
template += '</li>';
template += '<li class="divider" ng-show="settings.selectionLimit > 1"></li>';
template += '<li role="presentation" ng-show="settings.selectionLimit > 1"><a role="menuitem">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}</a></li>';
template += '</ul>';
template += '</div>';
element.html(template);
}
UI
<div ng-app="myModule" ng-controller="multiselect">
<div ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="lobs"
selected-model="lobsSelected" checkboxes="true">
</div>
</div>
Action Method n MVC Controller
public JsonResult GetALLLOB()
{
iMetricsEntities dbContext = new iMetricsEntities();
return new JsonResult
{
Data = dbContext.Levels.Where(objlevel => objlevel.N_ParentID == 0 && objlevel.B_Active && objlevel.N_LevelTypeID == 4),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
if i create another div with same controller,directive it does not create 2nd dropdown. doing this it disturbs first dropdown as well...
The answer is
1.create another div inside ng-app "mymodule"
<div class="row" ng-app="myModule" ng-controller="multiselect">
<div class="col-md-2">
<div id="lob" ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="lobs"
selected-model="lobsSelected" checkboxes="true">
</div>
</div>
<div class="col-md-2">
<div id="projects" ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="projects"
selected-model="projectsSelected" checkboxes="true">
</div>
</div>
</div>
2. write one more method within angular controller
$http.get('Home/GetALLLOB').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.lobs.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
$http.get('Home/GetAllProjects').then(function (data) {
debugger;
angular.forEach(data.data, function (value, index) {
$scope.projects.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
3. Write its corresponding method in MVC controller
public JsonResult GetAllProjects()
{
iMetricsEntities dbContext = new iMetricsEntities();
return new JsonResult
{
Data = dbContext.Levels.Where(objlevel => objlevel.N_ParentID == 0 && objlevel.B_Active && objlevel.N_LevelTypeID == 4),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

Delete a row and disable checkbox in dropdown-multiselect at the same time angularsjs

I have a problem with angularsJs, I have a dropdown-multiselect which contain a checkbox button with labels, when I click check, the label is addded in the table,
now, I want to delete a row in the table, so I have to click (supprimer) button (in the table) and I need in the same time that the check will be uncheked and I don't know how to proceed
Please some one could help me please
this is my popup.html page :
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/angular.js"></script>
<script src="js/angular-resource.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.0/lodash.min.js"></script>
<script src="js/MyApp.js"></script>
<link href="font-awesome-4.6.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body >
<div ng-app="myApp" ng-controller="AppCtrl">
<div ng-dropdown-multiselect="" options="example14data" selected-model="example14model" checkboxes="true" extra-settings="example14settings"></div>
<form class="form-inline" role="form" style="margin-left: 300px;">
<div class="form-group">
<input type="text" size="30" placeholder=" other subject" class="form-control" ng-model="otherSubject" />
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="ajouteSubject(otherSubject)" >Ajouter</button>
<button ng-click="supprimer()"> <a><i class="fa fa-remove" ng-click="supprimer()"></i></a>supprimer</button>
</div>
</form><br>
<table class="table table-responsive table-bordered" style="width:400px; margin-left: 300px;">
<thead>
<tr>
<th>Subject Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="pref in example14model">
<td>{{pref.label}}</td>
<td> <input type="checkbox" ng-model="pref.isDelete"/> {{$index}}</td>
</tr>
</tbody>
</table>
<br><br>
<pre>Selected Subject: {{example14model}} | </pre>
</div>
</body>
</html>
and My controller myApp.js
'use strict';
var app = angular.module('myApp', ['angularjs-dropdown-multiselect']);
app.controller('AppCtrl', function ($scope) {
$scope.example14model = [];
$scope.example14settings = {
scrollableWidth: '400px',
scrollableHeight: '200px',
scrollable: true,
enableSearch: true
};
$scope.example14data = [
{ "label": "JAVA", "id": "1" },
{ "label": "C++", "id": "2" },
{ "label": "JSON", "id": "3" },
{ "label": "DotNet", "id": "4"},
{"label": "AKKA", "id": "5"}
];
$scope.example2settings = {
displayProp: 'label'
};
$scope.ajouteSubject = function (otherSubject) {
$scope.example14data.push({
label: otherSubject,
checked: false
})
};
$scope.supprimer= function (){
var example14dataNew= [];
angulars.forEach($scope.example14data, function(v){
if (!v.isDelete){
example14dataNew.push(v);
}
$scope.example14data= example14dataNew;
} )
};
$scope.sessions = [{
id: 0
}];
});
var directiveModule = angular.module('angularjs-dropdown-multiselect', []);
directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
function ($filter, $document, $compile, $parse) {
return {
restrict: 'AE',
scope: {
selectedModel: '=',
options: '=',
extraSettings: '=',
events: '=',
searchFilter: '=?',
translationTexts: '=',
groupBy: '#'
},
template: function (element, attrs) {
var checkboxes = attrs.checkboxes ? true : false;
var groups = attrs.groupBy ? true : false;
var template = '<div class="multiselect-parent btn-group dropdown-multiselect" style="width: 300px">';
template += '<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} <span class="caret"></span></button>';
template += '<ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" >';
template += '<li ng-hide="!settings.showCheckAll || settings.selectionLimit > 0"><a data-ng-click="selectAll()"><i class="fa fa-check"></i> {{texts.checkAll}}</a>';
template += '<li ng-show="settings.showUncheckAll"><a data-ng-click="deselectAll();"><i class="fa fa-remove"></i> {{texts.uncheckAll}}</a></li>';
template += '<li ng-hide="(!settings.showCheckAll || settings.selectionLimit > 0) && !settings.showUncheckAll" class="divider"></li>';
template += '<li ng-show="settings.enableSearch"><div class="dropdown-header"><input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /></li>';
template += '<li ng-show="settings.enableSearch" class="divider"></li>';
if (groups) {
template += '<li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header">{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}</li>';
template += '<li ng-repeat-end role="presentation">';
} else {
template += '<li role="presentation" ng-repeat="option in options | filter: searchFilter">';
}
template += '<a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))">';
if (checkboxes) {
template += '<div class="checkbox"><label><input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}</label></div></a>';
} else {
template += '<span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"></span> {{getPropertyForObject(option, settings.displayProp)}}</a>';
}
template += '</li>';
template += '<li class="divider" ng-show="settings.selectionLimit > 1"></li>';
template += '<li role="presentation" ng-show="settings.selectionLimit > 1"><a role="menuitem">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}</a></li>';
template += '</ul>';
template += '</div>';
element.html(template);
},
link: function ($scope, $element, $attrs) {
var $dropdownTrigger = $element.children()[0];
$scope.toggleDropdown = function () {
$scope.open = !$scope.open;
};
$scope.checkboxClick = function ($event, label) {
$scope.setSelectedItem(label);
$event.stopImmediatePropagation();
};
$scope.externalEvents = {
onItemSelect: angular.noop,
onItemDeselect: angular.noop,
onSelectAll: angular.noop,
onDeselectAll: angular.noop,
onInitDone: angular.noop,
onMaxSelectionReached: angular.noop
};
$scope.settings = {
dynamicTitle: true,
scrollable: false,
scrollableWidth: '300px',
scrollableHeight: '300px',
closeOnBlur: true,
displayProp: 'label',
idProp: 'label',
externalIdProp: 'label',
enableSearch: false,
selectionLimit: 0,
showCheckAll: true,
showUncheckAll: true,
closeOnSelect: false,
buttonClasses: 'btn btn-default',
closeOnDeselect: false,
groupBy: $attrs.groupBy || undefined,
groupByTextProvider: null,
smartButtonMaxItems: 0,
smartButtonTextConverter: angular.noop
};
$scope.texts = {
checkAll: 'Check All',
uncheckAll: 'Uncheck All',
selectionCount: 'checked',
selectionOf: '/',
searchPlaceholder: 'Search...',
buttonDefaultText: 'Select a subject',
dynamicButtonTextSuffix: 'checked'
};
$scope.searchFilter = $scope.searchFilter || '';
if (angular.isDefined($scope.settings.groupBy)) {
$scope.$watch('options', function (newValue) {
if (angular.isDefined(newValue)) {
$scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
}
});
}
angular.extend($scope.settings, $scope.extraSettings || []);
angular.extend($scope.externalEvents, $scope.events || []);
angular.extend($scope.texts, $scope.translationTexts);
$scope.singleSelection = $scope.settings.selectionLimit === 1;
function getFindObj(label) {
var findObj = {};
if ($scope.settings.externalIdProp === '') {
findObj[$scope.settings.idProp] = label;
} else {
findObj[$scope.settings.externalIdProp] = label;
}
return findObj;
}
function clearObject(object) {
for (var prop in object) {
delete object[prop];
}
}
if ($scope.singleSelection) {
if (angular.isArray($scope.selectedModel) && $scope.selectedModel.length === 0) {
clearObject($scope.selectedModel);
}
}
if ($scope.settings.closeOnBlur) {
$document.on('click', function (e) {
var target = e.target.parentElement;
var parentFound = false;
while (angular.isDefined(target) && target !== null && !parentFound) {
if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
if (target === $dropdownTrigger) {
parentFound = true;
}
}
target = target.parentElement;
}
if (!parentFound) {
$scope.$apply(function () {
$scope.open = false;
});
}
});
}
$scope.getGroupTitle = function (groupValue) {
if ($scope.settings.groupByTextProvider !== null) {
return $scope.settings.groupByTextProvider(groupValue);
}
return groupValue;
};
$scope.getButtonText = function () {
if ($scope.settings.dynamicTitle && ($scope.selectedModel.length > 0 || (angular.isObject($scope.selectedModel) && _.keys($scope.selectedModel).length > 0))) {
if ($scope.settings.smartButtonMaxItems > 0) {
var itemsText = [];
angular.forEach($scope.options, function (optionItem) {
if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);
var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);
itemsText.push(converterResponse ? converterResponse : displayText);
}
});
if ($scope.selectedModel.length > $scope.settings.smartButtonMaxItems) {
itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
itemsText.push('...');
}
return itemsText.join(', ');
} else {
var totalSelected;
if ($scope.singleSelection) {
totalSelected = ($scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
} else {
totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
}
if (totalSelected === 0) {
return $scope.texts.buttonDefaultText;
} else {
return totalSelected + ' ' + $scope.texts.dynamicButtonTextSuffix;
}
}
} else {
return $scope.texts.buttonDefaultText;
}
};
$scope.getPropertyForObject = function (object, property) {
if (angular.isDefined(object) && object.hasOwnProperty(property)) {
return object[property];
}
return '';
};
$scope.selectAll = function () {
$scope.deselectAll(false);
$scope.externalEvents.onSelectAll();
angular.forEach($scope.options, function (value) {
$scope.setSelectedItem(value[$scope.settings.idProp], true);
});
};
$scope.deselectAll = function (sendEvent) {
sendEvent = sendEvent || true;
if (sendEvent) {
$scope.externalEvents.onDeselectAll();
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
} else {
$scope.selectedModel.splice(0, $scope.selectedModel.length);
}
};
$scope.setSelectedItem = function (label, dontRemove) {
var findObj = getFindObj(label);
var finalObj = null;
if ($scope.settings.externalIdProp === '') {
finalObj = _.find($scope.options, findObj);
} else {
finalObj = findObj;
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
angular.extend($scope.selectedModel, finalObj);
$scope.externalEvents.onItemSelect(finalObj);
if ($scope.settings.closeOnSelect) $scope.open = false;
return;
}
dontRemove = dontRemove || false;
var exists = _.findIndex($scope.selectedModel, findObj) !== -1;
if (!dontRemove && exists) {
$scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
$scope.externalEvents.onItemDeselect(findObj);
} else if (!exists && ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length < $scope.settings.selectionLimit)) {
$scope.selectedModel.push(finalObj);
$scope.externalEvents.onItemSelect(finalObj);
}
if ($scope.settings.closeOnSelect) $scope.open = false;
};
$scope.isChecked = function (label) {
if ($scope.singleSelection) {
return $scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp]) && $scope.selectedModel[$scope.settings.idProp] === getFindObj(label)[$scope.settings.idProp];
}
return _.findIndex($scope.selectedModel, getFindObj(label)) !== -1;
};
$scope.externalEvents.onInitDone();
}
};
}]);
Try this:
Replace:
<td> <a><i class="fa fa-remove" ng-click="supprimer()"></i></a>supprimer</td>
With this:
<td> <a><i class="fa fa-remove" ng-click="supprimer($index)"></i></a>supprimer</td>
And then in your controller do this:
$scope.supprimer = function(index) {
$scope.example14model.splice(index, 1);
}
Good luck :)

AngularJS UI Bootstrap dismiss() won´t work

Let me start by saying that I am very new to angular.
I have tried to setup a modal ui which works fine. But when I click the "cancel" button on the interface nothing happens.
This is my code:
(function () {
var domainName = 'TournamentCategory';
angular.module('tournamentCategories').controller("CategoriesController",
['$scope', '$modal', 'guidGenerator', 'eventBus', domainName + "Service",
'TournamentCategoryModelFactory',
function ($scope, $modal, guidGenerator, eventBus, domainService, modelFactory)
{$scope.openTournamentTree = function () {
var modalInstance = $modal.open({
templateUrl: 'TournamentTreeModal.html',
controller: 'TreeController',
size: 'wide-90',
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
//$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
}]);
})();
The HTML:
<script type="text/ng-template" id="TournamentTreeModal.html">
<div class="modal-header">
</div>
<div class="modal-body">
<div class="include-tree" ng-include="'tournament-tree.html'"></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">GEM</button>
<button ng-click="cancel()" class="btn btn-warning" type="button" data-dismiss="modal">LUK, uden at gemme</button>
</div>
This is my "treeController"
angular.module('tournamentTree').controller("TreeController", ['$scope', 'guidGenerator', function ($scope, guidGenerator) {
$scope.allMatches = [];
$scope.finalMatch = [createNewMatch()];
$scope.tierCount = 1;
$scope.previousMatchTier = 0;
$scope.deletePreviousMatches = function (parentMatch) {
for (var i in parentMatch.previousMatches) {
var previousMatch = parentMatch.previousMatches[i];
_.remove($scope.allMatches, function (match) { return match.id == previousMatch.id });
}
parentMatch.previousMatches = [];
}
$scope.addMatches = function (thisMatch) {
if (thisMatch && !thisMatch.previousMatches)
thisMatch.previousMatches = [];
if (thisMatch && thisMatch.previousMatches.length == 0) {
thisMatch.previousMatches.push(createNewMatch(thisMatch));
thisMatch.previousMatches.push(createNewMatch(thisMatch));
}
}
$scope.addMatchTier = function () {
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
$scope.addMatches(match);
}
}
$scope.tierCount++;
}
$scope.previousMatchTier = function () {
for (var i in $scope.allMatches) {
var previous;
if (previous.allMatches.length == i) {
previous = $scope.allMatches[i] - $scope.allMatches[i - 1];
}
}
}
$scope.removeMatchTier = function () {
//if (confirm('Er du sikker på, at du vil slette det yderste niveau af turneringstræet?')) {
var matchesToDelete = [];
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
matchesToDelete.push(match.nextMatch);
//$scope.deletePreviousMatches(match.nextMatch);
}
}
for (var i in matchesToDelete) {
$scope.deletePreviousMatches(matchesToDelete[i]);
}
$scope.tierCount--;
//}
}
$scope.hasPreviousMatches = function (match) {
return match && match.previousMatches && match.previousMatches.length > 0;
}
$scope.moveWinnerToNextMatch = function (match, winnerName) {
match.nextMatch.setPlayerName(match.id, winnerName);
}
function createNewMatch(nextMatch) {
var newMatch = {};
newMatch.tier = nextMatch && nextMatch.tier ? nextMatch.tier + 1 : 1;
newMatch.id = guidGenerator.newGuid();
newMatch.player1 = "";
newMatch.player2 = "";
newMatch.nextMatch = nextMatch;
newMatch.previousMatches = [];
newMatch.setPlayerName = function(matchId, playerName) {
for (var i in newMatch.previousMatches)
{
if (newMatch.previousMatches[i].id == matchId)
{
if (i == 0)
newMatch.player1 = playerName;
else
newMatch.player2 = playerName;
}
}
}
$scope.allMatches.push(newMatch);
return newMatch;
}
}]);
$dismiss is already available on modal scope so in template raplace cancel() with $dimiss() http://angular-ui.github.io/bootstrap/#/modal
That needs to go in your modals controller 'TreeController'
angular.module('tournamentCategories').controller('TreeController', function($scope, $modalInstance) {
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
});
I have an example in this plunker

Resources