Display a value from an object based on an id in AngularJS - angularjs

I'm currently using a custom filter to display a name when a user id is displayed. So selected_user might be 5, so it then displays "bob" instead of "5":
{{ selected_user | display_name:users }}
The users object contains the entire users table.
The code:
angular.module('myApp', []);
function xCtrl($scope) {
$scope.users = [
{"id":1, "name":"joe"},
{"id":5, "name":"bob"},
{"id":10, "name":"charlie"},
];
$scope.select_user = function(user) {
$scope.selected_user = user;
}
}
angular.module('myApp').filter("display_name", function () {
return function (user_id, users) {
if(user_id) {
return(users[users.map(function(x) { return x.id; }).indexOf(user_id)].name);
}
}
});
This works fine, but it feels like I am doing this inefficiently by passing the entire users object to the filter each time a name is displayed. Is there a better way to do this with filters or are filters the wrong approach?
Demo: http://jsfiddle.net/h2rn3qnw/

One approach is to have the ng-click directive return the $index:
<div ng-repeat="user_data in users"
ng-click="select($index)" class="selection">
{{ user_data.id }} - {{ user_data.name }} - {{$index}}
</div>
$scope.select = function(index) {
$scope.selection = index;
};
Selected User ID: {{ users[selection].id }}<br>
Selected User Name: {{ users[selection].name }}
The DEMO
angular.module('myApp', [])
.controller("xCtrl", function xCtrl($scope) {
$scope.users = [
{"id":1, "name":"joe"},
{"id":5, "name":"bob"},
{"id":10, "name":"charlie"},
];
$scope.select = function(index) {
$scope.selection = index;
};
})
.selection { color:blue; cursor:pointer; }
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app='myApp'>
<div ng-controller="xCtrl">
Users:<br>
<div ng-repeat="user_data in users"
ng-click="select($index)" class="selection">
{{ user_data.id }} - {{ user_data.name }} - {{$index}}
</div> <!-- ng-repeat -->
<hr>
Selected User ID: {{ users[selection].id }}<br>
Selected User Name: {{ users[selection].name }}
</div> <!-- ng-controller -->
</div> <!-- ng-app -->

Related

ng-repeat unique values only (combine duplicates)

I have an ng-repeat like this:
<option ng-repeat="item in items | orderBy:'priority'"
value="{{item.SAC}}.{{item.difficulty}}">
{{item.SAC}}.{{item.difficulty}} - {{SACItem(item.SAC).description}}
</option>
I want it to combine any duplicates based on both item.SAC and item.difficulty if both of those are a duplicate of the repeat they should be combined, otherwise they can be seperate.
I tried the unique filter but I couldn't get it to work with 2 variables.
You can create a filter:
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.items = [
{ name: 'john', age:45 },
{ name: 'tim', age: 36 },
{ name: 'bob', age: 44 },
{ name: 'john', age: 45 }
];
});
app.filter('unique', function() {
var uniqueItems = [];
function exists(item, parms) {
return uniqueItems.some((i) => parms.every((p) => i[p] == item[p]));
}
return function(arr, name, age) {
if (arr) {
uniqueItems.length = 0;
angular.forEach(arr, function(item) {
if (!exists(item, [name,age])) {
uniqueItems.push(item);
}
});
return uniqueItems;
}
return arr;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.js"></script>
<div ng-app ="app" ng-controller="ctrl">
<h1>Original Array</h1>
<ul>
<li ng-repeat="item in items">
{{item.name }} - {{ item.age }}
</li>
</ul>
<h1>Unique Array</h1>
<ul>
<li ng-repeat="item in items | unique:'name':'age'">
{{item.name }} - {{ item.age }}
</li>
</ul>
</div>
You can also use this filter in the controller instead of the view:
app.controller('ctrl', function($scope, $filter) {
var items = [...];
$scope.items = $filter('unique')(items, 'name', 'age');
});

AngularJS - ng-repeat print me (user_id) first, then order by

I need to loop trough object of users but I want to place a concrete user (me) at the beginning.
Example
this.users = [
{
id: 1,
name: "Jane"
},
{
id: 2,
name: "John"
},
{
id: 3,
name: "Me"
},
{
id: 4,
name: "Mark"
}
];
<div ng-repeat="user in ctrl.users">
<!-- SOME OTHER TAGS -->
</div>
And I want it to be this
<div>
<!-- ME -->
</div>
<div>
<!-- JANE -->
</div>
<div>
<!-- JOHN -->
</div>
<div>
<!-- MARK -->
</div>
Is it posible to do it using orderBy or do I have to reorganize my array of users ?
You can use a custom function to do the sorting, see this fiddle
$scope.sortUsers = function (user) {
if (user.name === 'Me') {
// return blank so it's always first in the order
// you can also do 'return 0'; if the sorting is by ID.
return '';
}
// return user.id; if by sorting is by ID
return user.name;
};
Use this in the view
<div ng-repeat="user in users | orderBy: sortUsers">
{{user.name}}<br/>
</div>
For more information, you can also look at this thread and the docs.

Data-binding is not updating ng-repeat section

I'm new to angularjs and I have a data binding issue.
After each repeated line, I want to show a number of mutually exclusive options. These would be images using a background-image, and when the option is selected I add the css class 'selected' to the span containing the image.
I've simplified it below to show options A, B and C and to make the currently selected one bold. By clicking on A, B or C you change the option.
The inner ng-repeat section is not evaluated again (it seems) when the model changes, but as the "Debugging category" shows, the outer ng-repeat is re-evaluated and the "Debugging category" shows correctly that the category has been changed.
I'm clearly missing something about angularjs; how can I get the inner ng-repeat to re-evaluate to that the correct style is applied to the A, B and C options?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var testApp = angular.module('testApp', []);
testApp.controller('NamesCtrl', function ($scope) {
$scope.categories = [ 'A', 'B', 'C' ];
$scope.names = [
{ name: 'John', category: 'C' },
{ name: 'Cindy', category: 'A' },
{ name: 'Patrick', category: 'B' }
];
$scope.changeCategory = function(name, category) {
name.category = category;
};
});
</script>
<body ng-app="testApp">
<h1>Names</h1>
<div ng-controller="NamesCtrl">
<ul>
<li ng-repeat="name in names">
<span>{{name.name}}</span>
<span ng-repeat="category in categories" ng-init="selected = (category == name.category)">
<span ng-style="{'true': {'font-weight': 'bold'}, false: {}}[selected]" ng-click="changeCategory(name, category)">{{category}}</span>
</span>
<em>(Debugging category: {{name.category}})</em>
</li>
</ul>
</div>
</body>
ng-init expression is not watched and updated automatically whenever related scope property value changes, you could just solve this by removing ng-init and using the expression directly
<span ng-style="{'true': {'font-weight': 'bold'}}[category == name.category]"
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var testApp = angular.module('testApp', []);
testApp.controller('NamesCtrl', function ($scope) {
$scope.categories = [ 'A', 'B', 'C' ];
$scope.names = [
{ name: 'John', category: 'C' },
{ name: 'Cindy', category: 'A' },
{ name: 'Patrick', category: 'B' }
];
$scope.changeCategory = function(name, category) {
name.category = category;
};
});
</script>
<body ng-app="testApp">
<h1>Names</h1>
<div ng-controller="NamesCtrl">
<ul>
<li ng-repeat="name in names">
<span>{{name.name}}</span>
<span ng-repeat="category in categories" >
<span ng-style="{'true': {'font-weight': 'bold'}}[category == name.category]" ng-click="changeCategory(name, category)">{{category}}</span>
</span>
<em>(Debugging category: {{name.category}})</em>
</li>
</ul>
</div>
</body>

how get the list of selected items in angular.js

Here I am using angular.js to show a list of people
<div class="recipient" ng-repeat="person in people">
<img src="{{person.img}}" /> person.name
<div class="email">person.email</div>
</div>
$scope.people = [{id:1}, {id:2}, {id:3}, {id:4}];
The looks is like below
What I want to do is I can select multiple items and by click a OK button, I can get a list of selected items. so If I select id 1 and id 2, then I want to get return a list of [{id:1},{id:2}]
How could I implement it in angular.js
Well I guess that if you're looping through a collection of people using a ng-repeat, you could add the ng-click directive on each item to toggle a property of you're object, let's say selected.
Then on the click on your OK button, you can filter all the people that have the selected property set to true.
Here's the code snippet of the implementation :
<div class="recipient" ng-repeat="person in people" ng-click="selectPeople(person)">
<img src="{{person.img}}" /> person.name
<div class="email">person.email</div>
</div>
<button ng-click="result()">OK</button>
function demo($scope) {
$scope.ui = {};
$scope.people = [{
name: 'Janis',
selected: false
}, {
name: 'Danyl',
selected: false
}, {
name: 'tymeJV',
selected: false
}];
$scope.selectPeople = function(people) {
people.selected = !people.selected;
};
$scope.result = function() {
$scope.ui.result = [];
angular.forEach($scope.people, function(value) {
if (value.selected) {
$scope.ui.result.push(value);
}
});
};
}
.recipient {
cursor: pointer;
}
.select {
color:green;
}
.recipient:hover {
background-color:blue;
}
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
<div ng-app ng-controller="demo">
<div class="recipient" ng-repeat="person in people" ng-click="selectPeople(person)" ng-class="{ select: person.selected }">
<div class="name">{{ person.name }}</div>
</div>
<button ng-click="result()">OK</button>
Result :
<ul>
<li ng-repeat="item in ui.result">{{ item.name }}</li>
</ul>
</div>
If you only want to show checked or unchecked you could just apply a filter, but you would need to toggle the filter value from undefined to true if you didn't wan't to get stuck not being able to show all again.
HTML:
<button ng-click="filterChecked()">Filter checked: {{ checked }}</button>
<div class="recipient" ng-repeat="person in people | filter:checked">
<input type='checkbox' ng-model="person.isChecked" />
<img ng-src="{{person.img}}" />{{ person.name }}
<div class="email">{{ person.email }}</div>
</div>
Controller:
// Apply a filter that shows either checked or all
$scope.filterChecked = function () {
// if set to true or false it will show checked or not checked
// you would need a reset filter button or something to get all again
$scope.checked = ($scope.checked) ? undefined : true;
}
If you want to get all that have been checked and submit as form data you could simply loop through the array:
Controller:
// Get a list of who is checked or not
$scope.getChecked = function () {
var peopleChkd = [];
for (var i = 0, l = $scope.people.length; i < l; i++) {
if ($scope.people[i].isChecked) {
peopleChkd.push(angular.copy($scope.people[i]));
// Remove the 'isChecked' so we don't have any DB conflicts
delete peopleChkd[i].isChecked;
}
}
// Do whatever with those checked
// while leaving the initial array alone
console.log('peopleChkd', peopleChkd);
};
Check out my fiddle here
Notice that person.isChecked is only added in the HTML.

How do I cancel drag between different lists when using angular-ui's sortable module

I am using angular-ui's sortable-ui module and am trying to raise a cancel so that the dragged items returns to it original location in the source list. Unfortunately I cannot get this working. Here is an example:
http://jsfiddle.net/Ej99f/1/
var myapp = angular.module('myapp', ['ui.sortable']);
myapp.controller('controller', function ($scope) {
$scope.list = ["1", "2", "3", "4", "5", "6"];
$scope.list2 = ["7", "8", "9"];
$scope.sortableOptions = {
update: function(e, ui) {
if (Number(ui.item.text()) === 6) {
ui.item.parent().sortable('cancel');
}
},
receive: function(e, ui) {
ui.sender.sortable('cancel');
ui.item.parent().sortable('cancel');
},
connectWith: ".group",
axis: 'y'
};
});
angular.bootstrap(document, ['myapp']);
Any help would be gratefully appreciated.
well, when it comes to angular, all roads lead to the data "the single source of truth". So update your model back to it's original state, before the move, and you're all set :)
example below has two lists, the first one being restricted for
its sorting (the update method)
and for sending an item (receive method on list 2)
the second list you can sort, and send items to list 1
(using foundation4 for css)
<div ng-app="test">
<div ng-controller="sortableTest">
<div class="small-4 columns panel">
<ul data-drop="true"
ui-sortable="sortable.options.list1" ng-model="sortable.model.list1">
<li ng-repeat="fruit in sortable.model.list1"
data-id="{{ fruit.id }}">{{ fruit.label }}</li>
</ul>
</div>
<div class="small-4 columns panel">
<ul data-drop="true"
ui-sortable="sortable.options.list2" ng-model="sortable.model.list2">
<li ng-repeat="element in sortable.model.list2"
data-id="{{ element.id }}">{{ element.label }}</li>
</ul>
</div>
<div class="clear"></div>
<br />
<span ng-repeat="fruit in sortable.model.list1">{{ fruit.label }} </span><br />
<span ng-repeat="element in sortable.model.list2">{{ element.label }} </span><br />
<span ng-repeat="fruit in sortable.oldData.list1">{{ fruit.label }} </span><br />
<span ng-repeat="element in sortable.oldData.list2">{{ element.label }} </span><br />
</div>
</div>
js:
var test = angular.module('test', ['ui.sortable']);
test.controller('sortableTest', function($scope, $timeout) {
$scope.sortable = {
model: {
list1: [{id: 1, label: 'apple'},{id: 2, label: 'orange'},{id: 3, label: 'pear'},{id: 4, label: 'banana'}],
list2: [{id: 5, label: 'earth'},{id: 6, label: 'wind'},{id: 7, label: 'fire'},{id: 8, label: 'water'}]
},
oldData: {
list1: [],
list2: []
},
options: {
list1: {
update: function(event, ui) {
console.debug('up-list1');
$scope.sortable.oldData.list1 = $scope.sortable.model.list1.slice(0);
$scope.sortable.oldData.list2 = $scope.sortable.model.list2.slice(0);
// DO NOT USE THIS! it messes up the data.
// ui.item.parent().sortable('cancel'); // <--- BUGGY!
// uncomment and check the span repeats..
$timeout(function(){
$scope.sortable.model.list1 = $scope.sortable.oldData.list1;
$scope.sortable.model.list2 = $scope.sortable.oldData.list2;
});
},
connectWith: 'ul'
},
list2: {
update: function(event, ui) {
console.debug('up-list2');
},
connectWith: 'ul',
receive: function(event, ui) {
console.debug('re-list2');
$timeout(function(){
$scope.sortable.model.list1 = $scope.sortable.oldData.list1;
$scope.sortable.model.list2 = $scope.sortable.oldData.list2;
});
}
}
}
};
});
you can of course use a service or something to store the old value. One can use ui.sender to differentiate the senders, if you have more that two..

Resources