Pass plain value to model Select2 angular-ui - angularjs

I use select2 from angular-ui, everything works ok, but it passes to ng-model object and I need to get plain value
this is in controller
$scope.units = {
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0; }).length===0) {
return {id:term, text:term};
}
},
multiple: false,
data: [{id: 0, text: 'kg'},{id: 1, text: 'ks'},{id: 2, text: 'm'}, {id: 3, text: 'h'}]
};
and this in view
<input type="hidden" class="form-control" id="unit_name" ui-select2="units" ng-model="newItem.unit">
but result is {id: 0, text: 'kg'} and I would need only text from that object. I know that is is possible to get it with .val(), but I not able to use with angular... So how to format output? Is it possible?
Thanks

I also have this problem, and i got solution by remove some line of code from the select2-ui.js.
Commnet following code in select2-ui.js
elm.bind("change", function(e) {
e.stopImmediatePropagation();
if (scope.$$phase || scope.$root.$$phase) {
return;
}
scope.$apply(function() {
controller.$setViewValue(
convertToAngularModel(elm.select2('data')));
});
});

Related

how to disable radio button dynamically in angularjs using ng-repeat

I have developing some code in Angular JS and i need to disable radio button based on previous selection or change in text box
in JS controller:
PPCO.cusGender = [ {
id : '1',
key : 'Male',
value : 'Male',
disable:false
}, {
id : '2',
key : 'Female',
value : 'Female',
disable:false
}, {
id : '3',
key : 'TG',
value : 'TG',
disable:false
}];
PPCO.changeapplicant = function() {
switch (PPCO.p_SALUTATION.toLowerCase().trim()) {
case 'mrs.':
case 'miss.':angular.forEach(PPCO.cusGender, function(val, key) {
if(val.key != 'Male')
{
val.disable = false;
}
});
break;
}
};
in HTML:
<input type="text" ng-model="PPCO.changeapplicant" class="color" ng-change="PPCO.changeapplicant()">
<label class="radio" ng-repeat="option in PPCO.cusGender">
<input type="radio" name="gender"
ng-model="PPCO.cusgendername" value="{{option.value}}"
ng-disabled="option.disable">
<i></i>
</label>
My question is i able change the "ng-disabled =true" value but it is not enabling again. How to make that
I have created this plnkr for this case: https://plnkr.co/edit/F4JZcf6Nm5Csbxbg
I think you have 2 errors happening at the same time:
You're iterating over one array. So, you don't need to use angular.forEach, you can use array.forEach
Also, most important, you're setting false when the element is mrs. or miss. and it's ok. BUT, you're not setting back to true. So, you will have to include one else clause like this:
if (['mrs.', 'miss.'].includes($scope.applicant.toLowerCase().trim())) {
$scope.cusGender.forEach(function(element) {
element.disable = element.key == 'Male';
});
} else {
$scope.cusGender.forEach(function(element) {
element.disable = false;
});
}
I think that would be all!

Vue.js filtering on array

I am trying to filter an array using a computed property in vue.js. I would like to search on on multiple fields, name, state, tags etc.
My data:
events: [
{
id: 1,
name: 'Name of event',
url: '#',
datetime: '2017-05-10T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'ordinary',
'advanced'
]
},
{
id: 2,
name: 'Another event',
url: '#',
datetime: '2017-05-12T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'beginner'
]
},
{
id: 3,
name: 'Great event',
url: '#',
datetime: '2017-05-18T00:00:00Z',
description: 'The full text of the event',
state: 'NSW',
tags: [
'beginner'
]
}
]
},
The following function works as expected, however I cant work out how to have it search the items in 'tags' (commented out).
searchevents: function(){
let result = this.events
if (this.filterValue){
result = result.filter(event =>
event.name.toLowerCase().includes(this.filterValue.toLowerCase()) ||
event.state.toLowerCase().includes(this.filterValue.toLowerCase())
// event.tags.toLowerCase().values().includes(this.filterValue.toLowerCase())
)
}
return result
}
The following returns a blank array, this method works ok when i have done it in angular but not in vue.
searchevents2: function(){
var searchRegex = new RegExp(this.filterValue,'i')
this.events.filter(function(event){
return !self.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state)
})
}
Ideally I would either like to be able to list array items to filter by or just filter by the entire array.
Appreciate any help, first post here so be gentle. I have a lot more experience with Python than Javascript so i may also use incorrect terminology at times.
You weren't too far off.
For your searchEvents filter, you just needed to add the tag filter. Here's how you might do that.
searchevents: function(){
let result = this.events
if (!this.filterValue)
return result
const filterValue = this.filterValue.toLowerCase()
const filter = event =>
event.name.toLowerCase().includes(filterValue) ||
event.state.toLowerCase().includes(filterValue) ||
event.tags.some(tag => tag.toLowerCase().includes(filterValue))
return result.filter(filter)
}
Array.some() is a standard array method that returns true if any element of the array passes your test.
searchevents2: function(){
const searchRegex = new RegExp(this.filterValue,'i')
return this.events.filter(event =>
!this.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state))
}
With searchEvents2 you really only left an errant self in there. Either you needed to set self before you executed the filter, or, as I have done here, turned it into an arrow function.
Example.
const app = new Vue ({
el: '#app',
data: {
search: '',
userList: [
{
id: 1,
name: "Prem"
},
{
id: 1,
name: "Chandu"
},
{
id: 1,
name: "Shravya"
}
]
},
computed: {
filteredAndSorted(){
// function to compare names
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
return this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase())
}).sort(compare)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.."/>
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>

Updating object properties with objects Angular

I am new to angular so forgive me if I use the incorrect terminology! I would also prefer any solutions using the latest Angular version if possible :-) I have some fairly complex use cases.
One of these is a customer edit screen. I have already built the list page and customer details forms, this works well. This also posts back some JSON. I have removed this from my example.
Something that a user must set is a customers stages which can be multiple. Therefore i will use checkboxes.
What I do is load the current user into the scope, then modify its values. then save to a web service. However i have some complex properties and figuring out how to bind these is problematic.
i found this example here which i can get to work if i put the options on my controller directly (shown in code)
http://plnkr.co/edit/cqsADe8lKegsBMgWMyB8?p=preview
however I cannot bind the check boxes on the currentUser.pipe properties. Any help would be greatly appreciated!
kind regards
jim
//our object definitions are here
function User(Firstname, Lastname, Id) {
this.Firstname = Firstname;
this.Lastname = Lastname;
this.PersonId = Id;
this.uuid = "OG6FSDHG6DF86G89DSHGDF8G6";
//hold the customers source
this.source = 2;
//these are used to populate our selection boxes
this.pipe = new Object();
//PROBLEM CODE IS HERE
//I WOULD LIKE TO OUTPUT A CHECKBOX FOR EACH ITEM AND THEN UPDATE THE SELECTED VALUE WHEN A USER CLICK IT
this.pipe.stages = [
{ id: 1, text: 'STAGE 1', selected: true },
{ id: 2, text: 'STAGE 2', selected: false },
{ id: 3, text: 'STAGE 3', selected: true },
{ id: 4, text: 'STAGE 4', selected: false }
];
this.getFullName = function () {
return this.Firstname + " " + this.Lastname + " " + Id;
};
}
function UserController($scope) {
//called to populate the customers list
$scope.populateCustomers = function () {
//this will be populated form the server. I have extra code which allows th euser ot select the customer and edit it and this works fine.
//I have removed the superflous code
$scope.userList = [
new User("John", "Doe", 1),
new User("Henri", "de Bourbon", 2),
new User("Marguerite", "de Valois", 3),
new User("Gabrielle", "d'Estrées", 4)
];
};
$scope.populateCustomers();
// the currentUser pobject is loaded by the user and modified. This works fine
$scope.currentUser = $scope.userList[0];
//if i add the stages here i can get them to update however these are different for each
//customer and would like the state to be held accordingly
$scope.stages = [
{ id: 1, text: 'STAGE 1', selected: true },
{ id: 2, text: 'STAGE 2', selected: true },
{ id: 3, text: 'STAGE 3', selected: true },
{ id: 4, text: 'STAGE 4', selected: true }
];
}
Here are the templates i have used. This one works off scope.stages
stages from scope.stages<br />
<label ng-repeat="stage in stages">
<input type="checkbox" value="{{stage.name}}" ng-model="stage.selected">{{stage.name}}
</label>
<p>stages: {{stages}}</p>
And this is what i would like to do however it shows the check boxes but doesnt bind correctly.
stages from currentUser.pipe.stages<br />
<label ng-repeat="stage in currentUser.pipe.stages">
<input type="checkbox" value="{{stage.name}}" ng-model="stage.selected">{{stage.name}}
</label>
<p>stages: {{stages}}</p>
Everything works perfectly. I think you have print the wrong variable in the currentUser.pipe.stages template. It will be <p>stages: {{currentUser.pipe.stages}}</p>.
stages from currentUser.pipe.stages<br />
<label ng-repeat="stage in currentUser.pipe.stages">
<input type="checkbox" value="{{stage.name}}" ng-model="stage.selected">{{stage.name}}
</label>
<!-- Print currentUser.pipe.stages -->
<p>stages: {{currentUser.pipe.stages}}</p>
See this PLUNKER. Its binding properly.

Not getting value of default selected checkbox

I am trying to get the of checkbox selected and store its result in an array . when the checkboxes are selected by default its not getting its value but after toggling if if a particular checkbox is selected its
working correctly.Please tell me what i am doing wrong and thanks in advance.
here my html code:
<div ng-repeat="album in albums" ng-disabled="checked">
<input type="checkbox" ng-model="album.selected" value={{album.value}} ng-checked = "true"/> {{album.name}}
</div>
<button ng-click = "setAlbums()" type = "submit" class = "col-sm-3 btn btn-primary" style = "margin-left:3%;"> Save </button>
here my js code:
$scope.albums = [{
value: 3,
name: 'a'
},
{
value: 4,
name: 'b'
},
{
value: 5,
name: 'c'
},
{
value: 6,
name: 'd'
},
{
value: 7,
name: 'd'
},
{
value: 8,
name: 'e'
},
{
value: 9,
name: 'f'
}];
$scope.setAlbums = function () {
$scope.albumNameArray = [];
angular.forEach($scope.albums, function(album){
if (album.selected) $scope.albumNameArray.push(album.value);
});
console.log("$scope.albumNameArray",$scope.albumNameArray)
}
Initially while ng-repeat is rendering the array it will look for the album.selected value in the array itself, so if its not able to find it, it will be virtually checked due to your ng-checked = true attribute but it will not be set in the ng-model, so
try it like this, use a another property called ng-init = "album.selected = true" in,
<input type="checkbox" ng-model="album.selected" value="{{album.value}}" ng-checked="true" ng-init="album.selected = true"/>
then try with the save button click.
PLUNKER WITH YOUR CODE

Error when passing filter parameter in Uigrid with cell nav

I have a editable Uigrid with ui-grid-cellnav directive to enable edit on focus. I also have a filter to display value instead of id in the dropdown.
<div ui-grid="gridOptions" ui-grid-edit ui-grid-cellnav class="grid"></div>
JS
$scope.gridOptions.columnDefs = [
{ name:'name', width:100 },
{ name:'age', width:100},
{ name: 'gender', displayName: 'Gender', editableCellTemplate: 'ui-grid/dropdownEditor', width: '20%',
cellFilter: "griddropdown:this", editDropdownIdLabel:'id',
editDropdownValueLabel: 'gender', editDropdownOptionsArray: [
{ id: 1, gender: 'male' },
{ id: 2, gender: 'female' }
] }
];
An error occurs whenever the dropdown value is modified. It seems the filter parameter is passed as a string instead of actual object, but not sure why. Works ok if I remove the cellnav directive.
Plnkr
Thanks in advance!
Interesting, I played with it a little bit and it looks like you are getting the desired results, just that occasionally ui-grid likes to pass a string as a parameter instead of the object.
If you add a check for a string in your filter it looks like you will still be getting the desired results, that's if I am understanding properly:
String check to add:
if (typeof context !== 'string') {}
Full Filter:
.filter('griddropdown', function() {
return function (input, context) {
if (typeof context !== 'string') {
var map = context.col.colDef.editDropdownOptionsArray;
var idField = context.col.colDef.editDropdownIdLabel;
var valueField = context.col.colDef.editDropdownValueLabel;
var initial = context.row.entity[context.col.field];
if (typeof map !== "undefined") {
for (var i = 0; i < map.length; i++) {
if (map[i][idField] == input) {
return map[i][valueField];
}
}
} else if (initial) {
return initial;
}
}
return input;
};
});

Resources