app.js
$scope.add = function () {
$('#btn').click(function() {
// insert a SPAN tag with class="spn" at the end in all DIVs with class="cls"
$scope.data=[];
var add=' <input type="text" name="currency" id="autocomplete">' ;
$('div.cls').append(add);
i++;
$scope.count++;
});
}
$scope.autocomplete=function(){
var currencies = [
{ value: 'Afghan afghani' },
{ value: 'Albanian lek'},
{ value: 'Algerian dinar'},
{ value: 'European euro' }
];
// setup autocomplete function pulling from currencies[] array
$('#autocomplete').autocomplete({
lookup: currencies,
});
}
html
<div class="cls" id="idd"></div>
<button type="button" class="btn btn-default btn-sm" id="btn">
<span class="glyphicon glyphicon-plus"></span> Add
</button>
This auto complete function run without using as append.. but when i used it after appending text field like above it does not works.can anyone help me.
This sample show to you how can create autocomplete using Angular, without jQuery autocomplete.
var app = angular.module("app", []);
app.controller("ctrl", function ($scope, $filter) {
$scope.suggestions = [];
$scope.selectedData = [];
$scope.defaultData = [
{ value: "Afghan afghani" },
{ value: "Albanian lek" },
{ value: "Algerian dinar" },
{ value: "European euro" }
];
$scope.search = function () {
var length = $scope.autocomplete.length;
if (length === 0) {
$scope.suggestionsNotFound = false;
$scope.suggestions = [];
} else {
var result = $filter("filter")($scope.defaultData, { value: $scope.autocomplete });
$scope.suggestions = result;
$scope.suggestionsNotFound = false;
if (result.length === 0) {
$scope.suggestionsNotFound = true;
}
}
///select
$scope.select = function (item) {
var isExist = $filter("filter")($scope.selectedData, { value: item.value }, true)[0];
if (!isExist) {
$scope.selectedData.push(item);
$scope.autocomplete = null;
$scope.suggestions = [];
}
}
///remove
$scope.remove = function (index) {
$scope.selectedData.splice(index, 1);
}
}
});
.autocomplete span {
margin-left: 5px;
}
.autocomplete span i {
color: red;
cursor: pointer;
}
<!doctype html>
<html ng-app="app" ng-controller="ctrl">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="autocomplete">
<input class="form-control" type="text" ng-model="autocomplete" ng-change="search()" />
<div class="clearfix"></div>
<span class="label label-default" ng-repeat="data in selectedData">
{{data.value}}
<i ng-click="remove($index)" class="glyphicon glyphicon-remove"></i>
</span>
<ul class="list-group">
<li class="list-group-item" ng-repeat="suggestion in suggestions" ng-click="select(suggestion)">
{{suggestion.value}}
</li>
</ul>
<div class="alert alert-info" ng-if="suggestionsNotFound">
<b>[{{autocomplete}}] not found!</b>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
Related
I cant work with cookies well in vue.js. I want to show data on another page in history.
How can I save data from my calculator with cookies in vue.js ?
Code :
<template>
<html>
<body>
<div id="app">
<div class="container">
<div class="calculator">
<div class="answer">{{ answer }}</div>
<div class="display">{{ logList + current }}</div>
<div #click="clear" id="clear" class="btn operator">C</div>
<div #click="sign" id="sign" class="btn operator">+/-</div>
<div #click="percent" id="percent" class="btn operator">
%
</div>
<div #click="divide" id="divide" class="btn operator">
/
</div>
<div #click="append('7')" id="n7" class="btn">7</div>
<div #click="append('8')" id="n8" class="btn">8</div>
<div #click="append('9')" id="n9" class="btn">9</div>
<div #click="times" id="times" class="btn operator">*</div>
<div #click="append('4')" id="n4" class="btn">4</div>
<div #click="append('5')" id="n5" class="btn">5</div>
<div #click="append('6')" id="n6" class="btn">6</div>
<div #click="minus" id="minus" class="btn operator">-</div>
<div #click="append('1')" id="n1" class="btn">1</div>
<div #click="append('2')" id="n2" class="btn">2</div>
<div #click="append('3')" id="n3" class="btn">3</div>
<div #click="plus" id="plus" class="btn operator">+</div>
<div #click="append('0')" id="n0" class="zero">0</div>
<div #click="dot" id="dot" class="btn">.</div>
<div #click="equal" id="equal" class="btn operator">=</div>
</div>
</div>
</div>
</body>
</html>
</template>
I cant work with model well in vue.js. I want to show what happened to numbers on another page in history.
This is my script :
<script>
export default {
data() {
return {
logList: '',
current: '',
answer: '',
operatorClicked: true,
}
},
methods: {
append(number) {
if (this.operatorClicked) {
this.current = ''
this.operatorClicked = false
}
this.current = `${this.current}${number}`
},
addtoLog(operator) {
if (this.operatorClicked == false) {
this.logList += `${this.current} ${operator} `
this.current = ''
this.operatorClicked = true
}
},
clear() {
this.current = ''
this.answer = ''
this.logList = ''
this.operatorClicked = false
},
sign() {
if (this.current != '') {
this.current =
this.current.charAt(0) === '-'
? this.current.slice(1)
: `-${this.current}`
}
},
percent() {
if (this.current != '') {
this.current = `${parseFloat(this.current) / 100}`
}
},
dot() {
if (this.current.indexOf('.') === -1) {
this.append('.')
}
},
divide() {
this.addtoLog('/')
},
times() {
this.addtoLog('*')
},
minus() {
this.addtoLog('-')
},
plus() {
this.addtoLog('+')
},
equal() {
if (this.operatorClicked == false) {
this.answer = eval(this.logList + this.current)
} else {
this.answer = 'wrong!'
}
},
},
}
</script>
mounted() {
if (localStorage.data) {
this.data = JSON.parse(localStorage.data);
}
},
watch: {
data(newData) {
localStorage.data = newData;
}
}
You could do something like this to save your data in local storage, and then load it on a page refresh. Or you can move the watcher into method and have it be triggered by "save" button.
Please help me with this.
What's wrong? Thanks!
I had the same problem and it fixed adding this js part which I extracted from here
$(document).ready(function() {
$('.stepper').activateStepper();
})
function validateStepOne() {
// Extract the checked checkboxes from the first step
if($('.step').first().find('input[type="checkbox"]:checked').length)
return true;
return false;
}
function validateStepThree() {
var validation = true;
if($('.step:nth-child(3) input[type="text"]').val().indexOf('materialize') === -1)
validation = false;
if($('.step:nth-child(3) input[type="checkbox"]:checked').length === 0)
validation = false;
return validation;
}
function nextStepThreeHandler() {
if(validateStepThree())
$('.stepper').nextStep();
else {
$('.stepper ').destroyFeedback(); $('.stepper').getStep($('.stepper').getActiveStep()).addClass('wrong');
}
}
/* Materializecss Stepper - By Kinark 2016
// https://github.com/Kinark/Materialize-stepper
// JS v2.1.3
*/
var validation = $.isFunction($.fn.valid) ? 1 : 0;
$.fn.isValid = function() {
if(validation){
return this.valid();
} else {
return true;
}
};
if (validation) {
$.validator.setDefaults({
errorClass: 'invalid',
validClass: "valid",
errorPlacement: function (error, element) {
if(element.is(':radio') || element.is(':checkbox')) {
error.insertBefore($(element).parent());
} else {
error.insertAfter(element); // default error placement.
// element.closest('label').data('error', error);
// element.next().attr('data-error', error);
}
},
success: function (element) {
if(!$(element).closest('li').find('label.invalid:not(:empty)').length){
$(element).closest('li').removeClass('wrong');
}
}
});
// When parallel stepper is defined we need to consider invisible and
// hidden fields
if($('.stepper.parallel').length) $.validator.setDefaults({ignore:''});
}
$.fn.getActiveStep = function() {
var active = this.find('.step.active');
return $(this.children('.step:visible')).index($(active))+1;
};
$.fn.activateStep = function(callback) {
if($(this).hasClass('step')) return;
var stepper = $(this).closest('ul.stepper');
stepper.find('>li').removeAttr("data-last");
if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
$(this).addClass("step").stop().slideDown(400, function(){
$(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
stepper.find('>li.step').last().attr('data-last', 'true');
});
} else {
$(this).addClass("step").stop().css({'width':'0%','display': 'inherit'}).animate({width:'100%'}, 400, function(){
$(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
stepper.find('>li.step').last().attr('data-last', 'true');
});
}
};
$.fn.deactivateStep = function(callback) {
if(!$(this).hasClass('step')) return;
var stepper = $(this).closest('ul.stepper');
stepper.find('>li').removeAttr("data-last");
if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
$(this).stop().css({'transition':'none', '-webkit-transition':'margin-bottom none'}).slideUp(400, function(){
$(this).removeClass("step").css({'height':'auto','margin-bottom':'','transition':'margin-bottom .4s','-webkit-transition':'margin-bottom .4s'});
if(callback)callback();
stepper.find('>li').removeAttr("data-last");
stepper.find('>li.step').last().attr('data-last', 'true');
});
} else {
$(this).stop().animate({width:'0%'}, 400, function(){
$(this).removeClass("step").hide().css({'height':'auto', 'margin-bottom': '','display': 'none', 'width': ''});
if(callback)callback();
stepper.find('>li.step').last().attr('data-last', 'true');
});
}
};
$.fn.showError = function(error) {
if(validation) {
var name = this.attr('name');
var form = this.closest('form');
var obj = {};
obj[name] = error;
form.validate().showErrors(obj);
this.closest('li').addClass('wrong');
} else {
this.removeClass('valid').addClass('invalid');
this.next().attr('data-error', error);
}
};
$.fn.activateFeedback = function() {
var active = this.find('.step.active:not(.feedbacking)').addClass('feedbacking').find('.step-content');
active.prepend('<div class="wait-feedback"> <div class="preloader-wrapper active"> <div class="spinner-layer spinner-blue"> <div class="circle-clipper left"> <div class="circle"></div></div><div class="gap-patch"> <div class="circle"></div></div><div class="circle-clipper right"> <div class="circle"></div></div></div><div class="spinner-layer spinner-red"> <div class="circle-clipper left"> <div class="circle"></div></div><div class="gap-patch"> <div class="circle"></div></div><div class="circle-clipper right"> <div class="circle"></div></div></div><div class="spinner-layer spinner-yellow"> <div class="circle-clipper left"> <div class="circle"></div></div><div class="gap-patch"> <div class="circle"></div></div><div class="circle-clipper right"> <div class="circle"></div></div></div><div class="spinner-layer spinner-green"> <div class="circle-clipper left"> <div class="circle"></div></div><div class="gap-patch"> <div class="circle"></div></div><div class="circle-clipper right"> <div class="circle"></div></div></div></div></div>');
};
$.fn.destroyFeedback = function() {
var active = this.find('.step.active.feedbacking');
if(active) {
active.removeClass('feedbacking');
active.find('.wait-feedback').remove();
}
return true;
};
$.fn.resetStepper = function(step) {
if(!step) step = 1;
var form = $(this).closest('form');
$(form)[0].reset();
Materialize.updateTextFields();
return $(this).openStep(step);
};
$.fn.submitStepper = function(step) {
var form = this.closest('form');
if(form.isValid()) {
form.submit();
}
};
$.fn.nextStep = function(callback, activefb, e) {
var stepper = this;
var settings = $(stepper).data('settings');
var form = this.closest('form');
var active = this.find('.step.active');
var next = $(this.children('.step:visible')).index($(active))+2;
var feedback = active.find('.next-step').length > 1 ? (e ? $(e.target).data("feedback") : undefined) : active.find('.next-step').data("feedback");
// If the stepper is parallel, we want to validate the input of the current active step. Not all elements.
if((settings.parallel && $(active).validateStep()) || (!settings.parallel && form.isValid())) {
if(feedback && activefb) {
if(settings.showFeedbackLoader) stepper.activateFeedback();
return window[feedback].call();
}
active.removeClass('wrong').addClass('done');
this.openStep(next, callback);
return this.trigger('nextstep');
} else {
return active.removeClass('done').addClass('wrong');
}
};
$.fn.prevStep = function(callback) {
var active = this.find('.step.active');
if(active.hasClass('feedbacking')) return;
var prev = $(this.children('.step:visible')).index($(active));
active.removeClass('wrong');
this.openStep(prev, callback);
return this.trigger('prevstep');
};
$.fn.openStep = function(step, callback) {
var settings = $(this).closest('ul.stepper').data('settings');
var $this = this;
var step_num = step - 1;
step = this.find('.step:visible:eq('+step_num+')');
if(step.hasClass('active')) return;
var active = this.find('.step.active');
var next;
var prev_active = next = $(this.children('.step:visible')).index($(active));
var order = step_num > prev_active ? 1 : 0;
if(active.hasClass('feedbacking')) $this.destroyFeedback();
active.closeAction(order);
step.openAction(order, function(){
if(settings.autoFocusInput) step.find('input:enabled:visible:first').focus();
$this.trigger('stepchange').trigger('step'+(step_num+1));
if(step.data('event')) $this.trigger(step.data('event'));
if(callback)callback();
});
};
$.fn.closeAction = function(order, callback) {
var closable = this.removeClass('active').find('.step-content');
if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
closable.stop().slideUp(300,"easeOutQuad", callback);
} else {
if(order==1) {
closable.animate({left: '-100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
} else {
closable.animate({left: '100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
}
}
};
$.fn.openAction = function(order, callback) {
var openable = this.removeClass('done').addClass('active').find('.step-content');
if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
openable.slideDown(300,"easeOutQuad", callback);
} else {
if(order==1) {
openable.css({left: '100%', display: 'block'}).animate({left: '0%'}, callback);
} else {
openable.css({left: '-100%', display: 'block'}).animate({left: '0%'}, callback);
}
}
};
$.fn.activateStepper = function(options) {
var settings = $.extend({
linearStepsNavigation: true,
autoFocusInput: true,
showFeedbackLoader: true,
autoFormCreation: true,
parallel: false // By default we don't assume the stepper is parallel
}, options);
$(document).on('click', function(e){
if(!$(e.target).parents(".stepper").length){
$('.stepper.focused').removeClass('focused');
}
});
$(this).each(function(){
var $stepper = $(this);
if(!$stepper.parents("form").length && settings.autoFormCreation) {
var method = $stepper.data('method');
var action = $stepper.data('action');
var method = (method ? method : "GET");
action = (action ? action : "?");
$stepper.wrap( '<form action="'+action+'" method="'+method+'"></form>' );
}
$stepper.data('settings', {linearStepsNavigation: settings.linearStepsNavigation,autoFocusInput: settings.autoFocusInput,showFeedbackLoader:settings.showFeedbackLoader, parallel:$stepper.hasClass('parallel')});
$stepper.find('li.step.active').openAction(1);
$stepper.find('>li').removeAttr("data-last");
$stepper.find('>li.step').last().attr('data-last', 'true');
$stepper.on("click", '.step:not(.active)', function () {
var object = $($stepper.children('.step:visible')).index($(this));
if($stepper.data('settings').parallel && validation) { // Invoke parallel stepper behaviour
$(this).addClass('temp-active');
$stepper.validatePreviousSteps()
$stepper.openStep(object + 1);
$(this).removeClass('temp-active');
} else if(!$stepper.hasClass('linear')) {
$stepper.openStep(object+1);
} else if(settings.linearStepsNavigation) {
var active = $stepper.find('.step.active');
if($($stepper.children('.step:visible')).index($(active))+1 == object) {
$stepper.nextStep(undefined, true, undefined);
} else if ($($stepper.children('.step:visible')).index($(active))-1 == object) {
$stepper.prevStep(undefined);
}
}
}).on("click", '.next-step', function(e) {
e.preventDefault();
$stepper.nextStep(undefined, true, e);
}).on("click", '.previous-step', function(e) {
e.preventDefault();
$stepper.prevStep(undefined);
}).on("click", "button:submit:not(.next-step, .previous-step)", function (e) {
e.preventDefault();
feedback = e ? $(e.target).data("feedback") : undefined;
var form = $stepper.closest('form');
if(form.isValid()) {
if(feedback) {
stepper.activateFeedback();
return window[feedback].call();
}
form.submit();
}
}).on("click", function () {
$('.stepper.focused').removeClass('focused');
$(this).addClass('focused');
});
});
};
/**
* Return the step element on given index.
*
* #param step, index of the step to be returned
* #returns {*}, the step requested
*/
$.fn.getStep = function(step) {
var settings = $(this).closest('ul.stepper').data('settings');
var $this = this;
var step_num = step - 1;
step = this.find('.step:visible:eq('+step_num+')');
return step;
};
/**
* Run validation over all previous steps from the steps this
* function is called on.
*/
$.fn.validatePreviousSteps = function() {
var active = $(this).find('.step.temp-active');
var index = $(this.children('.step')).index($(active));
// We assume that the validator is set to ignore nothing.
$(this.children('.step')).each(function(i) {
if (i >= index) {
$(this).removeClass('wrong done');
} else {
$(this).validateStep();
}
});
};
/**
* Validate the step that this function is called on.
*/
$.fn.validateStep = function() {
var stepper = this.closest('ul.stepper');
var form = this.closest('form');
var step = $(this);
// Retrieve the custom validator for that step if exists.
var validator = step.find('.next-step').data("validator");
if(this.validateStepInput()) { // If initial base validation succeeded go on
if(validator) { // If a custom validator is given also call that validator
if (window[validator].call()) {
step.removeClass('wrong').addClass('done');
return true;
}
else {
step.removeClass('done').addClass('wrong');
return false;
}
}
step.removeClass('wrong').addClass('done');
return true;
} else {
step.removeClass('done').addClass('wrong');
return false;
}
};
/**
* Uses the validation variable set by the stepper constructor
* to run standard validation on the current step.
* #returns {boolean}
*/
$.fn.validateStepInput = function() {
var valid = true;
if (validation) {
// Find all input fields dat need validation in current step.
$(this).find('input.validate').each(function() {
if (!$(this).valid()) {
valid = false;
return false;
}
});
}
return valid;
};
<head>
<!-- Materializecss compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/materialize-stepper#2.1.4/materialize-stepper.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!-- Materializecss compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<!-- jQueryValidation Plugin -->
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
</head>
<body class="container">
<form>
<ul class="stepper parallel horizontal">
<li class="step active">
<div class="step-title waves-effect waves-dark">Step 1</div>
<div class="step-content">
<div class="row">
<div class='form-field col s12'>
<p>Step with custom validation</p>
<span>For this step we want to have a custom validator that checks if if at least one checkbox is checked</span>
<p>
<input name='checkbox1' type="checkbox" class="filled-in"
id="checkbox1" value='checkbox1'/>
<label for="checkbox1">Checkbox 1</label>
</p>
<p>
<input name='checkbox2' type="checkbox" class="filled-in"
id="checkbox2" value='checkbox2'/>
<label for="checkbox2">Checkbox 2</label>
</p>
</div>
</div>
<div class="step-actions">
<button class="waves-effect waves-dark btn next-step" data-validator="validateStepOne">CONTINUE</button>
<button class="waves-effect waves-dark btn-flat previous-step">BACK</button>
</div>
</div>
</li>
<li class="step">
<div class="step-title waves-effect waves-dark">Step 2</div>
<div class="step-content">
<div class="row">
<div class='form-field col s12'>
<p>Step with no custom validation</p>
<div class="input-field col s12">
<input type="text" name="textfield" class="required validate"/>
<label for="textfield">Random textfield</label>
</div>
</div>
</div>
<div class="step-actions">
<button class="waves-effect waves-dark btn next-step">CONTINUE</button>
<button class="waves-effect waves-dark btn-flat previous-step">BACK</button>
</div>
</div>
</li>
<li class="step">
<div class="step-title waves-effect waves-dark">Step 3</div>
<div class="step-content">
<div class="row">
<div class='form-field'>
<p>Step with feedback and custom validation</p>
<p>
<input name='checkbox3' type="checkbox" class="filled-in"
id="checkbox3" value='checkbox3'/>
<label for="checkbox3">Checkbox 3</label>
</p>
<p>
<input name='checkbox4' type="checkbox" class="filled-in"
id="checkbox4" value='checkbox4'/>
<label for="checkbox4">Checkbox 4</label>
</p>
</div>
<div class="input-field col s12">
<input type="text" id="textfield2" name="textfield2" class="required validate"/>
<label for="textfield2">This field should contain the word materialize</label>
</div>
</div>
<div class="step-actions">
<button class="waves-effect waves-dark btn next-step" data-feedback="nextStepThreeHandler" data-validator="validateStepThree">SUBMIT</button>
<button class="waves-effect waves-dark btn-flat previous-step">BACK</button>
</div>
</div>
</li>
<li class="step">
<div class="step-title waves-effect waves-dark">Step 4</div>
<div class="step-content">
<div class="row">
<div class='form-field'>
<p>Submit phase</p>
</div>
</div>
<div class="step-actions">
<input type="submit" class="waves-effect waves-dark btn next-step" value="SUBMIT"/>
<button class="waves-effect waves-dark btn-flat previous-step">BACK</button>
</div>
</div>
</li>
</ul>
</form>
</body>
I am looking for a component like this to be included in my project:
http://geodan.github.io/duallistbox/sample-100.html
I want to install it with npm.
The problem is that I tested some of the examples which are over there, but without success (I get exceptions, or there is no npm, only bower)
These are the examples I tested.
https://github.com/alexklibisz/angular-dual-multiselect-directive
https://github.com/frapontillo/angular-bootstrap-duallistbox
http://www.bootply.com/mRcBel7RWm
Any recommendations about one with AngularJs, Bootstrap, and npm?
This might solve your requirement: Dual list Box
app.js
angular.module('plunker', [])
.controller('MainCtrl', function($scope, utils) {
$scope.list1 = [],
$scope.list2 = [];
utils.insertData($scope.list1, 5);
})
.factory('utils', function Utils() {
return {
insertData: function(list, numItems) {
for (var i = 0; i < numItems; i++) {
list.push({
id: i + 1,
title: 'item' + (i + 1)
});
}
},
getIndexesFromList: function(list) {
var newList = [];
for (var i in list) {
if (typeof list[i].id === "number" && newList.indexOf(list[i].id) === -1) newList.push(list[i].id)
}
return newList;
},
getAllSelectedItems: function(list) {
var newList = [];
newList = list.filter(function(el) {
return el.active === true;
});
return newList;
},
addListIfNoExists: function(list2, newListToAppend) {
var indexes = this.getIndexesFromList(list2);
var newList = [];
for (var i in newListToAppend) {
if (indexes.indexOf(newListToAppend[i].id) === -1) list2.push(newListToAppend[i])
}
return list2;
}
}
})
.directive('dualList', function(utils) {
function _controller($scope) {
$scope.selectAllItem = function(list, checked) {
list.map(function(item) {
item.active = checked
return item;
});
};
$scope.getAllSelectedItems = function(list) {
return utils.getAllSelectedItems(list);
}
$scope.moveItemToRightList = function() {
var newListToAppend = $scope.list1.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list1 = $scope.list1.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(el.id) === -1;
});
$scope.list2 = utils.addListIfNoExists($scope.list2, newListToAppend);
if ($scope.list1.length === 0) $scope.checked1 = false;
}
};
$scope.moveItemToLeftList = function() {
var newListToAppend = $scope.list2.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list2 = $scope.list2.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(parseInt(el.id)) === -1;
});
$scope.list1 = utils.addListIfNoExists($scope.list1, newListToAppend);
if ($scope.list2.length === 0) $scope.checked2 = false;
}
};
}
return {
restrict: "E",
scope: true,
controller: _controller,
templateUrl: "dualList.html"
};
});
dualList.html
<div class="container">
<br />
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked1"
ng-click="selectAllItem(list1, checked1)">
Todo {{getAllSelectedItems(list1).length}}/{{list1.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search1"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list1|filter: search1">{{item.title}}</a>
</ul>
<p ng-if="(list1 | filter:search1).length == 0">Sin Datos</p>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button ng-click="moveItemToLeftList()"
class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"></span>
</button>
<button ng-click="moveItemToRightList()"
class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked2"
ng-click="selectAllItem(list2, checked2)">
Todo {{getAllSelectedItems(list2).length}}/{{list2.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search2"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list2|filter: search2">{{item.title}}</a>
</ul>
<p ng-if="(list2 | filter:search2).length == 0">Sin Datos</p>
</div>
</div>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.angularjs.org/1.3.0/angular.js"></script>
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" />
<link data-require="font-awesome#*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<dual-list data-list1="list1" data-list2="list2"></dual-list>
</body>
</html>
style.css
.dual-list .list-group {
margin-top: 8px;
}
.list-arrows {
padding-top: 100px;
}
.list-arrows button {
margin-bottom: 20px;
}
.list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus {
border-color: white;
}
.input-group-addon {
top: 0;
}
I think this link will help you.
Try this npm for angular 2/4 just you need to install with npm
https://www.npmjs.com/package/ng2-dual-list-box
I am trying to grab the buttons html with .html() and insert into $scope.player. The button is calling the choosePlayer() function with ng-click but it is not working.
Here's the codepen link: http://codepen.io/theMugician/pen/ojJrRp
HTML
<body ng-app="ticTacToe" ng-controller="MainCtrl">
<div class="container">
<div class="row">
<div class="col-xs-12 text-center">
<h1>TIC TAC TOE</h1>
</div>
</div>
</div>
<div id="wrapper" class="container text-center">
<div class="row">
<div ng-click="move(cell)" ng-repeat="cell in cells" class="col-xs-4 square text-center">
{{cell.value}}
</div>
</div>
</div>
<div class="container">
<div class="row text-center">
<h1>CHOOSE A SHAPE</h1>
<button ng-click="choosePlayer()" class="btn btn-red" id="choose-cross">✖</button>
<button ng-click="choosePlayer()" class="btn btn-green" id="choose-circle">◯</button>
</div>
</div>
</body>
JAVASCRIPT
var app = angular.module("ticTacToe", []);
app.controller("MainCtrl", function($scope){
var cell = $(".square");
$scope.player = "";
var cross = "×";
var circle = "◯";
$scope.choosePlayer = function(){
$scope.player = $(this).html();
}
$scope.cells = [ { value: '' }, { value: '' }, { value: '' },
{ value: '' }, { value: '' }, { value: '' } ,
{ value: '' }, { value: '' }, { value: '' }
];
$scope.move = function(cell){
cell.value = $scope.player;
};
});
You could pass the $event object in the ng-click() directive:
<button ng-click="choosePlayer($event)" class="btn btn-red" id="choose-cross">✖</button>
<button ng-click="choosePlayer($event)" class="btn btn-green" id="choose-circle">◯</button>
And then access event.currentTarget to get the element in your controller:
Updated Example
Without jQuery:
$scope.choosePlayer = function(e) {
$scope.player = e.currentTarget.innerText;
}
With jQuery:
$scope.choosePlayer = function(e) {
$scope.player = $(e.currentTarget).text();
}
I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can't figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction
<div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>
Controller
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.
<ul ng-init="selectedTab = 'users'">
<li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
<li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
};
});
.red{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
</body>
Here is the example working on jsFiddle
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>
you can also do that in a directive, if you want to remove the previous class and add a new class
.directive('toggleClass', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
if(element.attr("class") == "glyphicon glyphicon-pencil") {
element.removeClass("glyphicon glyphicon-pencil");
element.addClass(attrs.toggleClass);
} else {
element.removeClass("glyphicon glyphicon-ok");
element.addClass("glyphicon glyphicon-pencil");
}
});
}
};
});
and in your template:
<i class="glyphicon glyphicon-pencil" toggle-class="glyphicon glyphicon-ok"></i>
You have it exactly right, all you have to do is set selectedIndex in your ng-click.
ng-click="selectedIndex = 1"
Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.
<div id="sidebar" ng-init="partial = 'main'">
<div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
</div>
and this in my controller.
$scope.router = function(endpoint) {
$location.path("/" + ($scope.partial = endpoint));
};
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
<div ng-show="isVisible" ng-class="{'active':isVisible}" class="block"></div>
I used Zack Argyle's suggestion above to get this, which I find very elegant:
CSS:
.active {
background-position: 0 -46px !important;
}
HTML:
<button ng-click="satisfaction = 'VeryHappy'" ng-class="{active:satisfaction == 'VeryHappy'}">
<img src="images/VeryHappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Happy'" ng-class="{active:satisfaction == 'Happy'}">
<img src="images/Happy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Indifferent'" ng-class="{active:satisfaction == 'Indifferent'}">
<img src="images/Indifferent.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Unhappy'" ng-class="{active:satisfaction == 'Unhappy'}">
<img src="images/Unhappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'VeryUnhappy'" ng-class="{active:satisfaction == 'VeryUnhappy'}">
<img src="images/VeryUnhappy.png" style="height:24px;" />
</button>
If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this
controller
(function() {
angular.module('MyApp', []).controller('MyController', MyController);
function MyController() {
var vm = this;
vm.tab = 0;
vm.setTab = function(val) {
vm.tab = val;
};
vm.toggleClass = function(val) {
return val === vm.tab;
};
}
})();
HTML
<div ng-app="MyApp">
<ul class="" ng-controller="MyController as myCtrl">
<li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
<li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
<li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
<li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
</ul>
CSS
.highlighted {
background-color: green;
color: white;
}
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
for Reactive forms -
HTML file
<div class="col-sm-2">
<button type="button" [class]= "btn_class" id="b1" (click)="changeMe()">{{ btn_label }}</button>
</div>
TS file
changeMe() {
switch (this.btn_label) {
case 'Yes ': this.btn_label = 'Custom' ;
this.btn_class = 'btn btn-danger btn-lg btn-block';
break;
case 'Custom': this.btn_label = ' No ' ;
this.btn_class = 'btn btn-success btn-lg btn-block';
break;
case ' No ': this.btn_label = 'Yes ';
this.btn_class = 'btn btn-primary btn-lg btn-block';
break;
}