I am building an Ionic app which has a list that is split using 'item divider'
The problem i am having is that when I use the buttons I have in the app to change the list order etc the divider text is not changing.
The divider text items are generated within an Angular directive.
I feel as though the problem is that the directive is not being re-called when the button is clicked.
Below is the code for the list and the directive.
I have also created a codepen to play about with if that makes things any easier.
Here is the CODEPEN LINK
Notice that when you use the search bar then delete the word the list does update
HTML/Ionic markup for the list
<ion-list id="list">
<ion-item
auto-list-divider
auto-list-divider-value="{{item[dividerString]}}"
auto-list-divider-function="dividerFunction"
ng-click="setDataSetClick(item.marker)"
ng-href="#/tab/films/{{item.id}}"
ng-repeat="item in outputData | filter:search.string | orderBy:dividerString:true">
<!-- If Film data show title p -->
<h3 ng-if="item.marker=='film';">{{item.title}}</h3>
<!-- If Cinema data show title p -->
<h3 ng-if="item.marker=='cinema';">{{item.cinema}}</h3>
</ion-item>
</ion-list>
Angular Controller
.controller('ListCtrl', function($scope, $timeout, $ionicScrollDelegate, Films, Cinemas, FilterList, OrderList, DataSetString, $ionicActionSheet) {
'use strict';
var cachedFilmData = Films.all(),
cachedCinemaData = Cinemas.all(),
indexedFilms = [];
$scope.dividerFunction = function(key) {
return key;
};
$scope.search = {
string: ''
};
$scope.dividerString = "year";
$scope.outputData = cachedFilmData;
$scope.filterString = FilterList.getFilter();
$scope.orderString = OrderList.getOrder();
$scope.itemsToFilter = function() {
indexedFilms = [];
return $scope.outputData;
};
$scope.filterFilms = function(films) {
var uniqueFilm = indexedFilms.indexOf(films[$scope.dividerString]) === -1;
if (uniqueFilm) {
indexedFilms.push(films[$scope.dividerString]);
}
return uniqueFilm;
};
$scope.setDataSetClick = function(data) {
DataSetString.setString(data);
};
// When the filter by button is clicked
$scope.showFilterActionSheet = function() {
$ionicActionSheet.show({
buttons: [{
text: 'Film'
}, {
text: 'Cinema'
}],
titleText: 'Select A Filter',
cancelText: 'Cancel',
buttonClicked: function(index, obj) {
FilterList.setFilter(obj.text);
$scope.filterString = FilterList.getFilter();
if ($scope.filterString === "Cinema") {
$scope.outputData = cachedCinemaData;
$scope.dividerString = "opened";
DataSetString.setString('cinema');
} else {
$scope.outputData = cachedFilmData;
$scope.dividerString = "year";
DataSetString.setString('film');
}
// Reset the order string tex
$scope.orderString = "Date";
return true;
}
});
};
// When the order by button is clicked
$scope.showOrderActionSheet = function() {
var activeDataSet = DataSetString.getString();
var optOne, optTwo, optThree;
if (activeDataSet === "cinema") {
optOne = "Opened";
optTwo = "Closed";
optThree = "Highlights";
} else {
optOne = 'Date';
optTwo = 'Themes';
optThree = 'Highlights';
}
$ionicActionSheet.show({
buttons: [{
text: optOne
}, {
text: optTwo
}, {
text: optThree
}],
titleText: 'Select An Order',
cancelText: 'Cancel',
buttonClicked: function(index, obj) {
var orderText = obj.text,
divider;
if (activeDataSet === "cinema") {
if (orderText === "Opened") {
divider = "opened";
}
if (orderText === "Closed") {
divider = "closed";
}
if (orderText === "Highlights") {
divider = "highlight";
}
sortData(cachedCinemaData, divider);
} else {
if (orderText === "Date") {
divider = "year";
}
if (orderText === "Themes") {
divider = "theme";
}
if (orderText === "Highlights") {
divider = "highlight";
}
sortData(cachedFilmData, divider);
}
$scope.orderString = obj.text;
$ionicScrollDelegate.scrollTop(true);
return true;
}
});
};
function sortData(data, divider) {
$scope.outputData = [];
var newOutputData = [];
for (var i = 0; i < data.length; i += 1) {
if (data[i][divider] != 0) {
console.log(divider);
newOutputData.push(data[i]);
}
}
$scope.outputData = newOutputData;
$scope.dividerString = divider;
}
})
Angular Directive
.directive('autoListDivider', function($timeout) {
var lastDivideKey = "";
return {
link: function(scope, element, attrs) {
var key = attrs.autoListDividerValue,
doDivide;
doDivide = function() {
var divideFunction = scope.$apply(attrs.autoListDividerFunction),
divideKey = divideFunction(key);
if (divideKey !== lastDivideKey) {
element.prepend(
'<h2 class="item item-divider custom--item-divider"><span ng-bind="divideKey">' + divideKey + '</span></h2>'
)
}
lastDivideKey = divideKey;
};
$timeout(doDivide, 0);
}
};
})
Related
Can someone please check my code in the codePen?
After adding the item to the list, It should log the total budget in the console.
It is only showing 0. Please see the code in the codePen console.
https://codepen.io/crazydeveloper/pen/KbKvMp
budCalc: function() {
var budget, percent, totalInc, totalExp;
totalInc = data.totals.inc;
totalExp = data.totals.exp;
budget = data.totals.inc - data.totals.exp;
percent = (data.totals.exp / data.totals.inc)*100
console.log(budget);
///////// BUDGET CONTROLLER ////////
var budgetController = (function() {
var Expence = function(id, des, value) {
this.id = id;
this.des = des;
this.value = value;
}
var Income = function(id, des, value) {
this.id = id;
this.des = des;
this.value = value;
}
var data = {
allItems: {
inc: [],
exp: []
},
totals: {
inc: 0,
exp: 0,
budget: 0,
percent: 0
}
}
return {
addItem: function(type, des, val) {
var newItem, id;
if (data.allItems[type].length > 0) {
var id = data.allItems[type][data.allItems[type].length - 1].id +
1;
} else {
id = 0;
}
if (type === "exp") {
newItem = new Expence(id, des, val);
} else if (type === "inc") {
newItem = new Income(id, des, val);
}
data.allItems[type].push(newItem);
return newItem;
},
calcTotal: function(type) {
sum = 0;
data.allItems[type].forEach(function() {
sum += data.totals[type];
data.totals[type] = data.totals[type] + sum;
}
)
},
budCalc: function() {
var budget, percent, totalInc, totalExp;
totalInc = data.totals.inc;
totalExp = data.totals.exp;
budget = data.totals.inc - data.totals.exp;
percent = (data.totals.exp / data.totals.inc)*100
console.log(budget);
var getBudget = function() {
return {
totalInc: totalInc,
totalExp: totalExp,
totalBudget: budget,
percent: percent
}
}
},
testing: function() {
console.log(data);
}
}
}());
////////// UI CONTROLLER //////////////
var UIController = (function() {
var DOMs = {
inpType: ".add__type",
inpDes: ".add__description",
inpVal: ".add__value",
inpBtn: ".add__btn",
incCon: ".income__list",
expCon: ".expenses__list"
}
return {
getInp: function() {
return {
type: $(DOMs.inpType).val(),
des: $(DOMs.inpDes).val(),
val: parseFloat($(DOMs.inpVal).val())
}
},
addListItem: function(obj, type) {
var html, newHTML, ele;
if(type === "inc") {
ele = DOMs.incCon;
html = '<div class="item clearfix" id="income-%id%"><div
class="item__description">%des%</div><div class="right clearfix"><div
class="item__value">+ %val%</div><div class="item__delete"><button
class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div></div></div>';
} else if(type === "exp") {
ele = DOMs.expCon;
html = '<div class="item clearfix" id="expense-%id%"><div
class="item__description">%des%</div><div class="right clearfix"><div
class="item__value">- %val%</div><div class="item__percentage">21%</div>
<div
class="item__delete"><button class="item__delete--btn"><i class="ion-ios-
close-outline"></i></button></div></div></div>';
}
newHTML = html.replace("%id%", obj.id);
newHTML = newHTML.replace("%des%", obj.des);
newHTML = newHTML.replace("%val%", obj.value);
$(ele).append(newHTML);
this.clearFields();
},
clearFields: function() {
$(DOMs.inpDes).add(DOMs.inpVal).val("");
$(DOMs.inpDes).focus();
},
getDOM: function() {
return DOMs;
}
}
}
());
////////// MAIN CONTROLLER /////////
var controller = (function(budgetCtrl, UICtrl) {
var eventLis = function() {
var DOM = UICtrl.getDOM();
$(DOM.inpBtn).on("click", eventBtn);
$("html").on("keypress", function() {
if (event.keyCode === 13 || event.which == 13) {
eventBtn();
}
})
}
function eventBtn() {
var input = UICtrl.getInp();
if(input.des !== "" && !isNaN(input.val) && input.val > 0) {
var newItem = budgetCtrl.addItem(input.type, input.des, input.val);
UICtrl.addListItem(newItem, input.type);
}
budgetCtrl.budCalc();
}
return {
init: function() {
console.log("Application started!");
eventLis();
}
}
})(budgetController, UIController);
controller.init();
This is all JavaScript code. But I can's figure out why my budget is not updating?
If you check the full data structure object at this point
budCalc: function() {
var budget, percent, totalInc, totalExp;
//here
console.log(data);
totalInc = data.totals.inc;
totalExp = data.totals.exp;
budget = data.totals.inc - data.totals.exp;
percent = (data.totals.exp / data.totals.inc)*100
}
You will see that data.total attributes are setted to zero everytime
I have a multiple dropdown and i want to show/hide based on change event on dropdown. It's nested elements dropdown.
http://jsfiddle.net/U3pVM/60518/
angular.module('myApp', []).controller('CEventCtrl', ['$rootScope', '$scope',
function($rootScope, $scope) {
var $this = this;
$this.bUOptions = '[{"id":"bu_0","options":[{"id":"","name":"Not Selected"},{"id":6,"name":"Bhumi1"},{"id":12,"name":"*Sales*"},{"id":17,"name":"*Support*"}],"label":"Department","showif":null},{"id":"bu_12","options":[{"id":"","name":"Not Selected"},{"id":13,"name":"AU Sales"},{"id":14,"name":"USA Sales"}],"label":"Section","showif":"bu_0=12"},{"id":"bu_14","options":[{"id":"","name":"Not Selected"},{"id":16,"name":"USA East Sales"},{"id":15,"name":"USA West Sales"}],"label":"Region","showif":"bu_12=14&&bu_0=12"},{"id":"bu_17","options":[{"id":"","name":"Not Selected"},{"id":18,"name":"AU Support"},{"id":19,"name":"UK Support"}],"label":"Section","showif":"bu_0=17"}]';
$scope.bUn = {};
this.count = 0;
this.isBUChildElement = function(value, key) {
this.bU = {};
bU = $this.bUOptions;console.log(bU);
if (value !== '' & typeof bU[key] == 'undefined') {
if (!$scope.bUn[key]) {
$scope.bUn[key] = false;
}
}
else {
$scope.bUn[key] = true;
};
return $scope.bUn[key];
}
this.getBUChild = function(selectedValue, showif,selectedElement){
var splitKey = selectedElement.split('_')[0];
angular.forEach(bUn, function(value, key){
if(splitKey+'_'+selectedValue !== key){
bUn[key] = false;
}
bUn[splitKey+'_'+selectedValue] = true;
});
if (showif !=='') {
if (showif.indexOf("&&") === -1) {
var splitShowif = showif.split('=');
console.log('');
console.log(splitKey+'_'+splitShowif[1]);
bUn[splitKey+'_'+splitShowif[1]] = true;
}
else {
var splitShowif = showif.split('&&');
angular.forEach(splitShowif, function(value, key) {
var splitShowifParts = value.split('=');
console.log('');
console.log(splitKey+'_'+splitShowifParts[1]);
bUn[splitKey+'_'+splitShowifParts[1]] = true;
});
}
}
bUn[selectedElement] = true;
}
}
]);
But somehow it is calling multiple times and not hide properly.
I have this case, I have a radio button for open a section called subscription. When clicked the section open with other 2 radio buttons, weekly and monthly. The weekly radio button is pre-selected and should be saved when I press the first radio opening the section and preserved. What I need to achieve here is also that a user can change the subscription to monthly and also this state should be preserved after save.
So when the user backs or refreshes the page the section subscription remain open with the chosen period. I would like to know the mofiication I have to do in my view and ctrl to reach the goal above mentioned.
The view:
<!--||| Subscribe Start |||-->
<div class="main-edit">
<div class="subsection">
<div class="flex-container row">
<div class="radiobutton-group">
<div class="width-140">
<input id="subscribed" type="checkbox" ng-model="analyticsEmailSettings.subscribed" value="subscribed" class="radiobutton" ng-click="modifySubscriptionType(type)">
<label class="label highlight inline no-bottom-margin" for="subscribed">
{{ 'user_settings_emailStatistics_subscribe' | translate }}
</label>
</div>
</div>
</div>
<div ng-show="analyticsEmailSettings.subscribed > 0">
<div class="flex-container row" ng-show="getUnselectedEngines().length > 0">
<div class="input-group flex-1" ng-switch="analyticsEmailSettings.subscription">
<label class="label" for="name">{{ 'user_settings_emailStatistics_recurrence' | translate }}</label>
<div class="inputs-container-row half-width" name="oftenReportSent">
<span class="radiobutton flex-1" ng-class="{'checked' : analyticsEmailSettings.subscription === 'WeeklyAnalytics'}" name="radio">
<input type="radio" name="WeeklyAnalytics"
ng-model="analyticsEmailSettings.subscription"
ng-checked="analyticsEmailSettings.subscription === 'WeeklyAnalytics'"
value="WeeklyAnalytics"
id="WeeklyAnalytics"
ng-required="">
<label for="WeeklyAnalytics">{{ 'user_settings_emailStatistics_weekly' | translate }}</label>
</span>
<span class="radiobutton flex-1" ng-class="{'checked' : analyticsEmailSettings.subscription === 'MonthlyAnalytics'}">
<input type="radio" name="MonthlyAnalytics"
ng-model="analyticsEmailSettings.subscription"
ng-checked="analyticsEmailSettings.subscription === 'MonthlyAnalytics'"
value="MonthlyAnalytics"
id="MonthlyAnalytics"
ng-required="">
<label for="MonthlyAnalytics">{{ 'user_settings_emailStatistics_monthly' | translate }}</label>
</span>
</div>
<!--<div> <span style="color:red;" ng-show="analyticsEmailSettings.subscription == null">Please select option</span></div>-->
</div>
</div>
The CTRL:
searchApp.controller('UserSettingsCtrl', ['$scope', '$q', '$rootScope', 'aiStorage', 'userConfig', 'UserSettingsService', 'WebsiteSource', 'AnalyticsEmailService', 'toaster', '$translate', '$timeout', 'ngTableParams',
function($scope, $q, $rootScope, store, userConfig, UserSettingsService, WebsiteSource, AnalyticsEmailService, toaster, $translate, $timeout, ngTableParams) {
$scope.init = function() {
$scope.availableLanguages = {
da: 'Dansk',
en: 'English',
sv: 'Svensk'
}
$scope.userInfo = store.get('user')
$scope.loadingAction = false
$scope.selectFlag = false
$scope.subscriptionEnginesFromServer = []
$scope.subscriptionEngines = []
$scope.analyticsEmailSettings = {}
$scope.analyticsEmailSettings.subscription = 'WeeklyAnalytics'
$scope.engines = angular.copy(WebsiteSource.sites)
AnalyticsEmailService.getUserSubscription().then(
function success(response) {
$scope.loadingAction = false
$scope.subscription = response
console.log('response.data', response.data)
$scope.subscriptionEnginesFromServer = populateSubscribedEnginesFromServer(response.data)
$scope.analyticsEmailSettings.subscribed = (response.data.length > 0)
},
function error() {})
}
function populateSubscribedEnginesFromServer(data) {
var subscriptionEngines = []
for (var i = 0; i < data.length; i++) {
var subscription = data[i]
var engine = $scope.engines.filter(function(x) {
return x.id === subscription.engine
})[0]
console.log('engine', engine)
if (engine) subscription.name = engine.name
subscriptionEngines.push(subscription)
}
console.log('subscriptionEngines', subscriptionEngines)
return subscriptionEngines
}
$scope.save = function() {
$scope.loadingAction = true
if ($scope.analyticsEmailSettings.subscribed) {
for (var i = 0; i < $scope.subscriptionEngines.length; i++) {
var obj = {
'type': $scope.subscriptionEngines[i].type,
'engine': $scope.subscriptionEngines[i].id || $scope.subscriptionEngines[i].engine,
'title': $scope.subscriptionEngines[i].name,
'name': $scope.subscriptionEngines[i].name
}
$scope.subscriptionEnginesFromServer.push(obj)
}
AnalyticsEmailService.updatesubscriptions($scope.subscriptionEnginesFromServer, function success(response) {}, function error() {})
$timeout(function() {
AnalyticsEmailService.getUserSubscription().then(
function success(response) {
$scope.loadingAction = false
$scope.subscription = response
$scope.analyticsEmailSettings.subscribed = (response.data.length > 0)
},
function error() {})
}, 1000)
} else {
AnalyticsEmailService.unsubscribe($scope.analyticsEmailSettings.subscription, function success(response) {}, function error() {})
}
UserSettingsService.save({
userId: $scope.userInfo.id
}, $scope.userInfo, function() {
$scope.loadingAction = false
userConfig.setCurrentUserConfig($scope.userInfo)
userConfig.setUserLocale()
store.set('user', $scope.userInfo)
toaster.pop({
type: 'success',
body: $translate.instant('notifications_user_settings_changed_success')
})
}, function() {})
$scope.subscriptionEngines = []
}
// removeSelectedEngines
$scope.getUnselectedEngines = function() {
if (!$scope.engines)
return []
var unselectedEngines = []
for (var i = 0; i < $scope.engines.length; i++) {
if ($scope.subscriptionEnginesFromServer.filter(function(x) {
return x.engine === $scope.engines[i].id
}).length == 0)
unselectedEngines.push($scope.engines[i])
}
// All engines
return unselectedEngines
}
$scope.addEngineToSubscriptionServer = function(engine) {
if ($scope.analyticsEmailSettings.subscription) {
engine.type = $scope.analyticsEmailSettings.subscription;
$scope.subscriptionEngines.push(engine);
$scope.save();
if ($scope.engine !== undefined)
$scope.engine.current = $scope.getUnselectedEngines()[0];
$scope.showMessage = true;
$scope.successMessage = "Subscription saved successfully!!!"
$timeout(function() {
$scope.showMessage = false;
}, 2000);
} else {
$scope.selectFlag = true
}
}
$scope.removeEngineFromSubscriptionServer = function(engine) {
var index = $scope.subscriptionEnginesFromServer.indexOf(engine)
$scope.subscriptionEnginesFromServer.splice(index, 1)
if ($scope.engine !== undefined)
$scope.engine.current = $scope.getUnselectedEngines()[0]
$scope.save()
}
$scope.modifySubscriptionType = function(engine) {
if ($scope.type == 'WeeklyAnalytics')
return $scope.analyticsEmailSettings.subscription = 'WeeklyAnalytics'
return $scope.analyticsEmailSettings.subscription
$scope.save()
}
// $scope.modifySubscriptions = function(engine, type, functionality) {
// var index = $scope.engines.indexOf(engine)
// $scope.engines[index].type = type
// if (functionality == 'add') {
// $scope.subscriptionEngines = []
// engine.type = 'WeeklyAnalytics'
// $scope.subscriptionEngines.push(engine)
// } else {
// for (var i = 0; i < $scope.subscriptionEnginesFromServer.length; i++) {
// if ($scope.subscriptionEnginesFromServer[i].engine == engine.id) {
// if (functionality == 'update')
// $scope.subscriptionEnginesFromServer[i].type = type
// else if (functionality == 'remove') {
// $scope.subscriptionEnginesFromServer.splice(i, 1)
// }
// break
// }
// }
// }
// $scope.save()
// }
}
])
ScreenShot:
The view section of the radio buttons involved
below code is about dual selectlist. as shown in below image.
Its working as desire. Only problem is, if I click on last subject from Right hand side list box (select Subject list), it is moving all subject to left list box. Technically it should only move the clicked (selected) one subject.
Any suggestion to resolve this?
Code is as following
(function () {
'use strict';
angular
.module("eSchoolSystem")
.directive('multiSelect',['$compile', '$log', multiSelect])
function multiSelect($compile, $log) {
return {
restrict: 'E',
scope: {
name: '#',
selectedModel: '=',
availableModel: '='
},
/*template: '<select id="{{name}}-available" multiple ng-model="availableModel" ng-click="toSelected()" ng-options="a as a.subjectShortName for a in Model.available"></select>\n\n\
<select id="{{name}}-selected" ng-click="toAvailable()" multiple ng-model="selectedModel" ng-options="s as s.subjectShortName for s in Model.selected"></select>',
*/
templateUrl:'app/class/html/dualMultiSelect.html',
compile: function() {
return {
pre: function($scope, $elem, $attr) {
var RefreshSelect = function(original, toFilter) {
var filtered = [];
angular.forEach(original, function(entity) {
var match = false;
for (var i = 0; i < toFilter.length; i++) {
if (toFilter[i]["subjectId"] === entity["subjectId"]) {
match = true;
break;
}
}
if (!match) {
filtered.push(entity);
}
});
return filtered;
};
var RefreshModel = function() {
/*$scope.selectedModel = $scope.Model.selected;*/
$scope.selectedModel = angular.copy($scope.Model.selected);
/*$scope.availableModel = $scope.Model.available;*/
$scope.availableModel = angular.copy($scope.Model.available);
};
var Init = function() {
$scope.Model = {
available: $scope.availableModel,
selected: $scope.selectedModel
};
$scope.selectedModel = [];
$scope.availableModel = [];
$scope.toSelected = function() {
$scope.Model.selected = $scope.Model.selected.concat($scope.availableModel);
$scope.Model.available = RefreshSelect($scope.Model.available, $scope.availableModel);
RefreshModel();
};
$scope.toAvailable = function() {
console.log("in here -x1")
console.log("x3-> " + JSON.stringify($scope.selectedModel))
$scope.Model.available = $scope.Model.available.concat($scope.selectedModel);
$scope.Model.selected = RefreshSelect($scope.Model.selected, $scope.selectedModel);
RefreshModel();
};
};
Init();
}
};
}
};
}
}());
Try to remove RefreshModel function and updating selected values in toSelected and toAvailable:
$scope.toSelected = function() {
$scope.Model.selected = $scope.Model.selected.concat($scope.availableModel);
$scope.Model.available = RefreshSelect($scope.Model.available, $scope.availableModel);
$scope.selectedModel = $scope.availableModel;
$scope.availableModel = [];
};
$scope.toAvailable = function() {
$scope.Model.available = $scope.Model.available.concat($scope.selectedModel);
$scope.Model.selected = RefreshSelect($scope.Model.selected, $scope.selectedModel);
$scope.selectedModel = [];
$scope.availableModel = $scope.selectedModel;
};
I am having trouble populating my multi-select. I am using this version of the multi-select http://davidstutz.github.io/bootstrap-multiselect/
I have looked at this stack overflow page (How can I use Bootstrap Multiselect Dropdown in AngularJS) but I am still having problems. I am trying to populate my multi-select with data that I grab from a database which gets stored in provData.
Here is my html:
<div class="col-sm-8">
<select class="form-control" multiple ht-multi-select ng-model="patient.provid" ng-options="prov.id as prov.code for prov in provData">
<option value="{{prov.id}}">{{prov.code}}</option>
</select>
</div>
Here is my directive:
templates.directive('htMultiSelect', function() {
return {
replace: true,
require: 'ngModel',
scope: {},
link:function(scope, element, attrs) {
console.log($(element));
console.log('hit');
// Below setup the dropdown:
$(element).multiselect({
enableClickableOptGroups: true
});
// Below maybe some additional setup
scope.$watch(attrs.ngModel, function () {
$(element).multiselect('refresh');
});
}
};
});
My main issue is I can not populate my multi-select with data from provData and I can not get it to set the ng-model. Any help will be greatly appreciated.
Based on Rashim's blog, this is what I tried in Plunke.
https://rashimuddin.wordpress.com/2014/07/08/multi-select-drop-down-in-angularjs/
Check this out
http://plnkr.co/edit/y8VOlgeSMOqHjFxoZU1L?p=previewenter code here
HTML
<div dropdown-multiselect="" items="FirstItems" on-close="closeAlert(val)" on-Validation="addAlert(validationMsg)" max-Selection="3" selected-items="FirstSelectedItems"></div>
Angular directive would be
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('AppCtrl', ["$scope", function($scope) {
$scope.status = {
isopen: false
};
$scope.FirstItems = [];
$scope.alerts = [{
type: 'danger',
msg: 'Oh snap! Change a few things up and try submitting again.'
}, {
type: 'success',
msg: 'Well done! You successfully read this important alert message.'
}];
$scope.addAlert = function(validationMsg) {
if ($scope.validateFire === true) {
$scope.alerts.push({
msg: validationMsg
});
}
$scope.validateFire = true;
};
$scope.closeAlert = function(val) {
$scope.alerts = [];
}
for (var i = 0; i <= 20; i++) {
var obj = [];
obj["Id"] = i;
obj["Name"] = "Name" + i;
obj["IsSelected"] = false;
$scope.FirstItems.push(obj);
}
$scope.FirstSelectedItems = [];
var removeItem = function(items, item) {
for (var index = 0; index < items.length; index++) {
if (item.Id == items[index].Id) {
item.IsSelected = false;
items.splice(index, 1);
break;
}
}
};
$scope.removeFirstItem = function(item) {
removeItem($scope.FirstSelectedItems, item);
};
$scope.removeSecondItem = function(item) {
removeItem($scope.SecondSelectedItems, item);
};}]);
Directive goes like this
app.directive('dropdownMultiselect', function() {
return {
restrict: 'A',
scope: {
items: "=",
selectedItems: "=",
maxSelection: "=",
validateFire: "=",
onValidation: '&',
onClose: '&'
},
template: "" +
"" +
"Add " +
"" +
"" +
"" +
"" +
"All " +
"None" +
"" +
"" +
"" +
" " +
"{{item.Name}}" +
"" +
"" +
"",
controller: function($scope) {
$scope.handleClick = function($event) {
$event.stopPropagation();
};
$scope.status = {
isopen: false
};
$scope.status = {
isopen: false
};
$scope.openDropdown = function($event) {
if ($scope.items !== undefined && $scope.items.length > 0) {
if ($scope.items.length > $scope.maxSelection)
$scope.showAll = false;
else
$scope.showAll = true;
for (var index = 0; index < $scope.items.length; index++) {
$scope.items[index].IsSelected = false;
}
if ($scope.selectedItems !== undefined && $scope.selectedItems.length > 0) {
for (var selectedItemIndex = 0; selectedItemIndex < $scope.selectedItems.length; selectedItemIndex++) {
for (var itemIndex = 0; itemIndex < $scope.items.length; itemIndex++) {
if ($scope.selectedItems[selectedItemIndex].Id == $scope.items[itemIndex].Id) {
$scope.items[itemIndex].IsSelected = true;
break;
}
}
}
}
}
$event.stopPropagation();
$scope.status.isopen = true;
};
$scope.selectAll = function($event) {
$scope.selectedItems = [];
angular.forEach($scope.items, function(item) {
item.IsSelected = true;
$scope.selectedItems.push(item);
});
$event.stopPropagation();
};
$scope.deselectAll = function($event) {
angular.forEach($scope.items, function(item) {
item.IsSelected = false;
});
$scope.selectedItems = [];
$event.stopPropagation();
};
$scope.selectItem = function(item) {
if (item.IsSelected === false) {
for (var index = 0; index < $scope.selectedItems.length; index++) {
if (item.Id == $scope.selectedItems[index].Id) {
item.IsSelected = false;
$scope.selectedItems.splice(index, 1);
$scope.onClose({
val: "1"
});
break;
}
}
} else {
if ($scope.selectedItems.length > $scope.maxSelection) {
item.IsSelected = false;
$scope.validationMsg = "MAX_REACHED";
$scope.validateFire = true;
$scope.onValidation({
validationMsg: "Max_Reached"
});
return;
}
$scope.selectedItems.push(item);
}
};
$scope.clickItem = function($event) {
$event.stopPropagation();
};
$scope.closeDropDown = function() {
$scope.status.isopen = false;
$event.stopPropagation();
};
}
};
});`