Angularjs ng-repeat race condition in setting dropdown value - angularjs

I had the problem of getting resource data from an API, loading that into a dropdown select, and setting the selected value of the dropdown. Basically it was trying to set the value of the dropdown before it was populated. I have two different ways to do this, but was wondering if anyone had a "better" way, or a "better practice" way. Here are my two ways.
Option 1: Directive attached to ng-repeat element
Controller
$scope.users = User.query();
$scope.dude={
name: "Dude",
id: 3
}
HTML
<select id="userSelect" ng-show="users.length">
<option ng-repeat="user in users" choose dude="dude">{{user.username}}</option>
</select>
Directive
.directive('choose', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
if (scope.user) {
if (scope.user.id === scope.dude.id) {
$("#userSelect").val(element.val());
}
}
}
}
});
Option 2: Watch for the users length to change (the call is returned, and the dropdown is populated)
Controller
$scope.users = User.query();
$scope.dude={
name: "Dude",
id: 3
}
$scope.$watch('users.length', function() {
$("#userSelect").val($scope.dude.id);
});
HTML
<select id="userSelect" ng-show="users.length">
<option ng-repeat="user in users" value="{{user.id}}>{{user.username}}</option>
</select>
Any opinions on which one is better practice? Or if there is any other better way?

So, promises are your friend for this sort of thing. I'm going to use $http instead of resources, because I'm more familiar with it, but I'm pretty sure recent version of
resources return promises (or can).
Also.. no jquery in your controllers. Use directives like ng-model to change input values.
Also using ng-options to populate the options for a select is more powerful than using ng-repeat on an "option" element.
Here's what a lot of my code looks like (except that I'm using jsonp here instead of just get). http://jsfiddle.net/HB7LU/142/
CONTROLLER:
function MyCtrl($scope, $http) {
// The id we want to select when the data loads:
var desiredId = 3;
// Overly complicated $http request so that I can load with jsonp:
// You could normally use just $http.get()
$scope.users = $http.jsonp('http://www.json-generator.com/j/geku?callback=JSON_CALLBACK').then(function(d) { return d.data.result; });
// Use the returned promise to set the selection when the data loads:
// I'm using the "underscore" library function "findWhere" to set my
// model to the object I want selected:
$scope.users.then(function(d) {
$scope.uservalue = _.findWhere(d,{id:desiredId});
});
}
HTML:
<div ng-controller="MyCtrl">
{{uservalue | json}}
<select ng-model="uservalue" ng-show="users.length" ng-options="user.name for user in users">
</select>
</div>

Related

Angular way of binding elements of the same name together

In angular, I have a list of checkboxes that are all binded to a value of boolean value that I get from a json:
<div ng-repeat="err in rec.errorList"><input type="checkbox" ng-model="err.ignore" name="{{err.errorCode}}" ng-value="err.errorCode" check-all="{{err.errorCode}}" /></div>
But mean while, I am trying to check all those checkboxes with the same name, when checking one of the checkboxes!
what is the best way of doing that in angular way? I mean is there a way of binding all these checkboxes with the same Name attribute for example, together?
I tried to write a directive, something like this but don't know how should I continue on that:
.directive("checkAll", function(){
return {
link: function(scope, element, attr){
element.bind('change', function(){
var errorCode = attr["checkAll"];
var elms = scope.errorCode;
})
}
}
})
Here is a plunker of what I actually want to do
http://plnkr.co/edit/sLXGlXRh9vu7FETDmJd1?p=preview
I can have many lists, and what I want to is whenever I click on one of these checkboxes, update all the checkboxes with the same errorCode maybe without looping on all those errorLists again.
You could do this simply using the same ng-model for each name.
This will look like this :
Controller
$scope.errorList = [{errorCode:1},{errorCode:2},
{errorCode:1},{errorCode:3},{errorCode:1},{errorCode:1},
{errorCode:2},{errorCode:1},{errorCode:3},{errorCode:3}];
$scope.checkboxByName = {};
View
<div ng-repeat="err in errorList">
<input type="checkbox" ng-model="checkboxByName[err.errorCode]">
</div>
If you really need the error.ignore var on each error, you could add this function :
$scope.updateIgnore = function(){
angular.forEach($scope.errorList, function(error){
error.ignore = $scope.checkboxByName[error.errorCode];
})
}
And a ng-change on all your inputs :
ng-change="updateIgnore()"
Here is a plunker showing the full implementation
Hope it helped.

Custom Directive : Dropdown selected value not binding

I'm trying to create a custom directive for a drop down control in AngularJS 1.4.4. I can handle the selected event, but i can not get the binding for what is selected in the drop down list.
I want to call this from Html markup the following way.
<my-dropdown-list source="myList" destination="mySelection" />
The angular js custom directive is here.
(function() {
var directive = function($compile) {
return {
restrict: 'E',
scope: {
model: '=source',
selectedValues: '=destination'
},
controller: function($scope) {
$scope.onSelChange = function() {
alert('called');
console.log($scope.selectedItem.Code, $scope.selectedItem.Name);
};
// $scope.selectedItem is always undefined here.
},
link: function ($scope, $elem) {
var rowHtml =
'<select ng-options="item as item.Name for item in model" ng-model="selectedItem" ng-change="onSelChange()"></select>';
$elem.html(rowHtml);
$compile($elem.contents())($scope.$new());
}
};
};
my.directive('myDropdownList', directive);
})();
I'm new to Angular, so this may be something small that i missed here, but i can't seem to get a value for 'selectedItem'
I find out this in AgularJS document
Note that the value of a select directive used without ngOptions is
always a string. When the model needs to be bound to a non-string
value, you must either explictly convert it using a directive (see
example below) or use ngOptions to specify the set of options. This is
because an option element can only be bound to string values at
present.
Link: https://docs.angularjs.org/api/ng/directive/select
You should use ngRepeat to generate the list like this post:
Angularjs: select not updating when ng-model is updated

AngularJS Dropdown Directive Set Selected Item Through Two Way Binding

I have an angularjs dropdown directive. I want to be able to pass the id of the item I want to be selected as an attribute of the directive. Something like this:
<dropdown selected-item-id="ctrl.selectedItemId"></dropdown>
I implemented this and it's not working. If I display the value of itemId on the directive code, I can see the right value, but the dropdown selection does not update. Here's the relevant code:
(function () {
'use strict';
var dropdown = function ($state, service) {
return {
restrict: 'E',
replace: true,
templateUrl: '/dropdown.html',
scope: {
selectedItemId:"="
},
link: function (scope, elem, attr) {
service
.getItems()
.then(function (items) {
scope.items = items;
});
}
};
};
dropdown.$inject = ['$state', 'service'];
angular.module('app').directive('dropdown', dropdown);
})();
<select class="form-control"
ng-model="selectedItemId"
ng-options="item.id as item.name for item in items">
<option value="" selected disabled>Select an item</option>
</select>
Like I said, if I display the selectedItemId on the directive template (e.g. as one of the options) I see the right id value, however the dropdown selection doesn't change.
Any thoughts?
EDIT:
I had a typo (happened when typing the code, the actual code on my editor is correct) on the dropdown's property, item-id to selected-item-id
You are not binding selected value to item-id as you think according to your html code. You are binding selected value to selected-item-id.
Try changing your html to this:
<dropdown selected-item-id="ctrl.selectedItemId"></dropdown>
Looks like you might be having a race condition on the $digest cycle. If you call $apply() from your service callback on the first version of your code it should work. However, you will have the side effect that from time to time angular will complain about an $apply being already in progress so the second version of your code should do the trick.
I'm not sure why it wasn't working like I had it, but I made some changes an now it works ok. Here's what I did (the explanation is included as comments on the source code):
//Here I use the selectedItem bidirectional binding on the .then of my service call
//to get the id of the items that's supposed to be selected.
//Then, I filter the array of items using that id, so I get the actual object that matches the id.
//Finally, I set the scope object "selectedItem" to that object I just got.
//The "selectedItem" object is what's bound to the select via ng-model so that does the selection.
(function () {
'use strict';
var dropdown = function ($state, service) {
return {
restrict: 'E',
replace: true,
templateUrl: '/dropdown.html',
scope: {
selectedItemId:"="
},
link: function (scope, elem, attr) {
service
.getItems()
.then(function (items) {
scope.items = items;
var selectedItem = $filter('filter')(items, { id: scope.selectedItemId })[0];
scope.selectedItem = selectedItem;
});
}
};
};
dropdown.$inject = ['$state', 'service'];
angular.module('app').directive('dropdown', dropdown);
})();
<!--Here I replaced the ng-model to use an object rather than an id and did the same on the ng-options -->
<select class="form-control"
ng-model="selectedItem"
ng-options="item as item.name for item in items">
<option value="" selected disabled>Select an item</option>
</select>

What is the "right" way in Angularjs of doing "master-detail" inter directive communication

I have a directive that displays a list of "master" items and when the user clicks on one of these items I want any "details" directives on the page (there could be more than one) to be updated with the details of the currently selected "master" item.
Currently I'm using id and href attributes as a way for a "details" directive to find its corresponding master directive. But my impression is that this is not the angular way, so if it's not, what would be a better solution?
I appreciate that typically when the issue of inter-communication between directives is raised then the obvious solutions are either to use require: "^master-directive" or to use a service, but in this case the directives are not in the same hierarchy and I don't think using a service is appropriate, as it would make the solution more complicated.
This is some illustrative code showing what I'm doing currently.
<div>
<master-list id="master1"></master-list>
</div>
<div>
<details-item href="#master1" ></details-item>
</div>
In the master-list directive when an item is selected I set an attribute to indicate the currently selected master item:
attrs.$set('masterListItemId',item.id);
In the details-item directive's link function I do:
if (attrs.href) {
var id = attrs.href.split('#')[1];
var masterList = angular.element(document.getElementById(id));
if (masterList) {
var ctrl = masterList.controller('masterList');
ctrl.attrs().$observe('masterListItemId',function(value) {
attrs.$set('detailItemId',value);
});
}
}
attrs.$observe('detailItemId',function(id) {
// detail id changed so refresh
});
One aspect that put me off from using a service for inter-directive communication was that it is possible (in my situation) to have multiple 'masterList' elements on the same page and if these were logically related to the same service, the service would end up managing the selection state of multiple masterList elements. If you then consider each masterList element had an associated detailItem how are the right detailItem elements updated to reflect the state of its associated masterList?
<div>
<master-list id="master1"></master-list>
</div>
<div>
<master-list id="master2"></master-list>
</div>
<div>
<details-item href="#master1" ></details-item>
</div>
<div>
<details-item href="#master2" ></details-item>
</div>
Finally I was trying to use directives, rather than using controller code (as has been sensibly suggested) as I'd really like the relationship between a masterList and its associated detailItems to be 'declared' in the html, rather than javascript, so it is obvious how the elements relate to each other by looking at the html alone.
This is particularly important as I have users that have sufficient knowledge to create a html ui using directives, but understanding javascript is a step too far.
Is there a better way of achieving the same thing that is more aligned with the angular way of doing things?
I think I would use a service for this. The service would hold the details data you care about, so it would look something like this.
In your master-list template, you might have something like a list of items:
<ul>
<li ng-repeat"item in items"><a ng-click="select(item)">{{item.name}}</a></li>
</ul>
...or similar.
Then in your directives, you would have (partial code only)
.directive('masterList',function(DetailsService) {
return {
controller: function($scope) {
$scope.select = function(item) {
DetailsService.pick(item); // or however you get and retrieve data
};
}
};
})
.directive('detailsItem',function(DetailsService) {
return {
controller: function($scope) { // you could do this in the link as well
$scope.data = DetailsService.item;
}
};
})
And then use data in your details template:
<div>Details for {{data.name}}</div>
<ul>
<li ng-repeat="detail in data.details">{{detail.description}}</li>
</ul>
Or something like that.
I would not use id or href, instead use a service to retrieve, save and pass the info.
EDIT:
Here is a jsfiddle that does it between 2 controllers but a directive would be the same idea
http://jsfiddle.net/u3u5kte7/
EDIT:
If you want to have multiple masters and details, leave the templates unchanged, but change your directive controllers and services as follows:
.directive('masterList',function(DetailsService) {
return {
controller: function($scope) {
$scope.select = function(item) {
DetailsService.pick($scope.listId,item); // or however you get and retrieve data
};
}
};
})
.directive('detailsItem',function(DetailsService) {
return {
controller: function($scope) { // you could do this in the link as well
$scope.data = DetailsService.get($scope.listId).item;
}
};
})
.factory('DetailsService',function(){
var data = {};
return {
pick: function(id,item) {
data[id] = data[id] || {item:{}};
// set data[id].item to whatever you want here
},
get: function(id) {
data[id] = data[id] || {item:{}};
return data[id];
}
};
})
I would opt for a different approach altogether without directives. Directives are ideal for DOM manipulation. But in this case I would stick to using just the template and a controller that manages all the data and get rid of the directives. Use ng-repeat to repeat the items
Check out this fiddle for an example of this: http://jsfiddle.net/wbrand/2xrne4k3
template:
<div ng-controller="ItemController as ic">
Masterlist:
<ul><li ng-repeat="item in ic.items" ng-click="ic.selected($index)">{{item.prop1}}</li></ul>
Detaillist:
<ul><li ng-repeat="item in ic.items" >
{{item.prop1}}
<span ng-if="item.selected">SELECTED!</span>
</li></ul>
</div>
controller:
angular.module('app',[]).controller('ItemController',function(){
this.items = [{prop1:'some value'},{prop1:'some other value'}]
this.selectedItemIndex;
this.selected = function(index){
this.items.forEach(function(item){
item.selected = false;
})
this.items[index].selected = true
}
})

Place element outside the controller and have them still work AngularJS

How can I control variables and elements using filters that are outside the controller?
I have set up an example to better help me explain my question http://embed.plnkr.co/7E5Ls3oH0q4HuEZsewJL/
You will see I have a div that is being toggled using ng-show and then inside a search input that filters a list of names. The problem arrises when I need to take the toggled div and the search filter and put it outside the 'MainCtrl'. Is there a way that I can have these sitting outside the controller but still interacting with the content of the 'MainCtrl'?
There are several ways to communicate between components which aren't prototypically linked in your app. You could use Angular events to broadcast your search and then handle it from your controller. Or, you could even use $rootScope in both components as a global space both can use to store variables and methods. These are bad ideas - they will make your life harder down the road.
Instead, whenever you need to share information across controllers and/or directives which aren't directly linked, your first thought should to create a service.
Such a service might look like this:
app.factory('Search', function() {
var search = {
results: [],
query: '',
showDetails: false
};
return search;
});
You would inject it into both the controller and the controller or directive (I chose to create a directive) for the search box and initialize the service to a scope variable in each:
app.controller('MainCtrl', function ($scope, friendsFactory, Search) {
$scope.friends = friendsFactory.query();
$scope.search = Search;
});
app.directive('search', function(Search){
return {
restrict: 'E',
scope: {},
templateUrl: 'directive-search.html',
link: {
pre: function(scope, elem, attrs) {
scope.search = Search;
}
}
}
});
You could use that variable in your views, as the model for the search box and the filter for your ng-repeat:
Directive Template
<div ng-class="'details'" ng-show="search.showDetails">
<label for="">Search Names</label>
<input type="text" ng-model="search.query" />
</div>
Filter
<div class="content" ng-controller="MainCtrl">
<a ng-click="search.showDetails = !search.showDetails"> Click Me</a>
<div ng-repeat="friend in friends | filter:search.query | limitTo: 5">
{{friend.name}}
</div>
</div>
Plunker Demo
Note: this simple implementation allows for one individual search/results pair on the page. If you need to have more than one, you will need to further develop the service to allow for more than one instance.

Resources