Angular - Trouble with ng-change - angularjs

I am still a little new to Angular, and I am having trouble setting the default select option, if that option is the only one in the array. What happens specifically is that the select does default, however, the shipping cost is not being calculated. It only calculates if the user chooses it from the drop down. I think the issue may be because with the ng-change on the select element, but I am not sure.
In my HTML:
<select class="form-control" ng-change="updateShipper()" name="shipMethod"
ng-model="currentOrder.LineItems[0].ShipperName"
ng-show="user.ShipMethod.ShipperSelectionType == 'UserDropDown'"
ng-options="shipper.Name as (shipper.Name + ' ' + (shipper.ShippingRate.Price | currency | xlat)) for shipper in shippers"
ng-required="!currentOrder.IsMultipleShip() && user.ShipMethod != null" >
<option value=""></option>
In my controller:
scope.$watch('shippers', function(val) {
if(angular.isDefined(val)){
$timeout(function() {
if(val.length === 1){
scope.currentOrder.LineItems[0].ShipperName = val[0].Name;
}
}, 0);
}
});
$scope.updateShipper = function(li) {
$scope.shippingUpdatingIndicator = true;
$scope.shippingFetchIndicator = true;
if (!li) { // at the order level
angular.forEach($scope.shippers, function(s) {
if (s.Name == $scope.currentOrder.LineItems[0].ShipperName)
$scope.currentOrder.Shipper = s;
});
angular.forEach($scope.currentOrder.LineItems, function(item) {
item.ShipperName = $scope.currentOrder.Shipper ? $scope.currentOrder.Shipper.Name : null;
item.ShipperID = $scope.currentOrder.Shipper ? $scope.currentOrder.Shipper.ID : null;
});
saveChanges(function() {
$scope.shippingUpdatingIndicator = false;
$scope.shippingFetchIndicator = false;
});
}
else { // at the lineitem level for multiple shipping
angular.forEach($scope.shippers, function(s) {
if (s.Name == li.ShipperName)
li.Shipper = s;
});
li.ShipperName = li.Shipper.Name;
li.ShipperID = li.Shipper.ID;
saveChanges(function() {
$scope.shippingUpdatingIndicator = false;
$scope.shippingFetchIndicator = false;
});
}
};

Try ng-init="updateShipper()". Then set the initial value of your model in the controller like $scope.currentOrder.LineItems[0].ShipperName = 0(or whatever).

Related

Truncate ng-bind-html in AngularJS

I'm using truncate.js https://github.com/sparkalow/angular-truncate and it works great for codes like this:
{{announcement.content | characters:25}}
However, i can't seem to setup for the following and i can't get it to work:
<p ng-bind-html="parseTrustedHtml(announcement.content | characters : 25)"></p>
I encountered a similar issue, the issue is that angular-truncate is meant for strings, not HTML. Here is my solution:
Markup:
<div class="container" ng-controller="parentCtrl">
<div ng-bind-html="text | limitHtml : maxNumberOfChar:'...' | trustAsHtml"></div>
</div>
Code:
.filter('trustAsHtml', ['$sce', function($sce) {
return $sce.trustAsHtml;
}])
.filter('limitHtml', function() {
return function(text, limit, ellipsis) {
var _getClosedTagsString = function(_tagArray) {
var _returnArray = [],
_getTagType = function(_string) {
return _string.replace(/<[\/]?([^>]*)>/,"$1");
};
angular.forEach(_tagArray,function(_tag,_i) {
if(/<\//.test(_tag)) {
if(_i === 0) {
_returnArray.push(_tag);
} else if(_getTagType(_tag) !== _getTagType(_tagArray[_i - 1])) {
_returnArray.push(_tag);
}
}
});
return _returnArray.join('');
},
_countNonHtmlCharToLimit = function(_text,_limit) {
var _isMarkup = false,
_isSpecialChar = false,
_break = false,
_underLimit = false,
_totalText = 0,
_totalChar = 0,
_element,
_return = {
textCounter : 0,
offsetCounter : 0,
setEllipsis : false,
overElementArray : []
};
angular.forEach(_text,function(_c) {
_underLimit = _return.textCounter < _limit;
if(_c === '<' && !_isMarkup && !_isSpecialChar) {
(!_underLimit) && (_element = '<');
_isMarkup = true;
} else if(_c === '&' && !_isMarkup && !_isSpecialChar) {
_isSpecialChar = true;
} else if(_isMarkup) {
//tracking html elements that are beyond the text limit
(!_underLimit) && (_element = _element + _c);
if(_c === '>') {
//push element in array if it is complete, and we are
//beyond text limit, to close any html that is unclosed
(!_underLimit) && (_return.overElementArray.push(_element));
_break = true;
_isMarkup = false;
}
} else if(_c === ';' && _isSpecialChar) {
_isSpecialChar = false;
//count as one character
_return.textCounter++;
_break = true;
}
if(_underLimit) {
if(!_isMarkup && !_isSpecialChar && !_break) {
//counting number of characters in non html string
_return.textCounter++;
}
_return.offsetCounter++;
} else {
_return.setEllipsis = true
}
_break = false;
});
//returns offset within html of number of non html characters found
return _return;
},
_charToLimitOutput = _countNonHtmlCharToLimit(text.toString(),limit);
return text.toString().substr(0, _charToLimitOutput.offsetCounter) +
ellipsis + _getClosedTagsString(_charToLimitOutput.overElementArray);
}
})
.controller('parentCtrl', function($scope,$timeout) {
$scope.text = "<span><h1>Example </h1><p>Special Text</p><div>other stuff</div></span>";
$scope.maxNumberOfChar = 10;
});
No need to use truncate.js
You can solve this using custom directives and filters.
try this one: https://stackoverflow.com/a/45076560/6816707
Need more information, however can you check if parseTrustedHtml method/function is available at $scope or $rootscope.

Angular JS radio lists and dropdowns. Issue with dropdowns changing value of radio list value when triggered

I think I have a logic issue with my Angular that I need some help on.
We have a service that connects to a DB that gets saved values so our Angular form can get the values and use them. That is all set up.
My issue is, in our form we have 1 radio button list using an ng-repeat to generate the list and 3 dropdown lists. Our dropdown lists are triggering and update function to update the values of themselves. We are showing and hiding the dropdown menus based on the radio button lists selection (I will post the code). This should be noted we are using Umbraco CMS that this control is being used for, but this is not the actual issue.
The issue is, we console our response the value of the radio button list outputs fine to the selection we chose, BUT when I select one of the dropdown list items, the value of the dropdown list returns to the previously selected value. Any help figuring this out would be greatly appreciated.
Code is below:
my.controller.js
angular.module("umbraco")
.controller("Our.GalaxyEventSelectorController", function ($scope, $routeParams, notificationsService, GalaxyEventSelectorResource) {
$scope.emptyList = [{}];
$scope.ETypeRadio = { 0: "NA", 1: "RepeatingTimedEvent", 2: "RepeatSingleDayEvent", 3: "SingleTimedEvent" };
GalaxyEventSelectorResource.getEventById($routeParams.id, $scope.model.alias).then(function (response) {
// console.log("REsponse: " + response);
console.log("intial load on DOM load")
var resp = (response.data.indexOf("{") > -1 ? angular.fromJson(JSON.parse(response.data)) : "");
$scope.previousSelectedTypeOfEvent = (resp == "" ? "" : resp.TypeOfEvent);
$scope.previousSelectedEventTypeId = (resp == "" ? 0 : resp.EventTypeId);
$scope.previousSelectedEventName = (resp == "" ? "" : resp.EventName);
$scope.previousSelectedEventId = (resp == "" ? 0 : resp.EventId);
$scope.previousSelectedEventDate = (resp == "" ? "" : resp.EventDate);
//This loads the selection the initial time.
$scope.selectedTypeOfEvent = $scope.previousSelectedTypeOfEvent; //THIS Gets the previous radio button selection
//init EventTypeId dropdown
var initIdx = 0;
$scope.getEventTypeIds(true, initIdx);
}).then(function() {
//init Name dropdown
var initIdx = -1;
$scope.getEventNames(true, initIdx, $scope.previousSelectedEventTypeId);
}).then(function () {
//init EventIds and Dates dropdowns
var initIdx = -1;
$scope.getEventIdsAndDates(true, initIdx, $scope.previousSelectedEventName);
$scope.getEventDatesOnly(true, initIdx, $scope.previousSelectedEventName);
}).then(function () {
// init model values
$scope.typeOfEventRadioSelected($scope.previousSelectedTypeOfEvent);
$scope.updateModelValue(
$scope.previousSelectedTypeOfEvent,
$scope.previousSelectedEventTypeId,
$scope.previousSelectedEventName,
$scope.previousSelectedEventId,
$scope.previousSelectedEventDate);
});
$scope.updateModelValue = function (typeOfEvent, eventTypeId, eventName, eventId, eventDate) {
$scope.model.value = {
TypeOfEvent: typeOfEvent,
EventTypeId: eventTypeId,
EventName: eventName,
EventId: eventId,
EventDate: eventDate
}
console.log("Scope load and scope change");
console.log($scope.model.value);
};
//not used...attempting to make the visual nice onscreen but causes unpredictable loss of data. could be useful
$scope.addSpacesToCamelCase = function(txt) {
return txt.replace(/([a-z])([A-Z])/g, "$1 $2");
}
$scope.typeOfEventRadioSelected = function(selectedTypeOfEvent) {
//triggered when radio button selected.
var typeOfEvent = selectedTypeOfEvent;
var eventTypeId = $scope.selectedGalaxyEventTypeId != null
? $scope.selectedGalaxyEventTypeId.EventTypeId
: "";
var eventName = "";
var eventId = "";
var eventDate = "";
var initIdx = -1;
$("#GalaxyEventNameDdl").show();
$("#GalaxyEventIdDdl").show();
$("#GalaxyEventDatesDdl").show();
switch (selectedTypeOfEvent) {
case "NA":
$scope.getEventNames(false, initIdx, eventTypeId);
$scope.GalaxyEventIdsAndDates = $scope.initial;
$scope.GalaxyEventDates = $scope.initial;
$("#GalaxyEventNameDdl").hide();
$("#GalaxyEventIdDdl").hide();
$("#GalaxyEventDatesDdl").hide();
break;
case "RepeatingTimedEvent":
//$scope.getEventNames(false, initIdx, eventTypeId);
eventName = $scope.selectedGalaxyEventName != null
? $scope.selectedGalaxyEventName.EventName
: "";
$scope.GalaxyEventIdsAndDates = $scope.initial;
$scope.GalaxyEventDates = $scope.initial;
$("#GalaxyEventIdDdl").hide();
$("#GalaxyEventDatesDdl").hide();
break;
case "RepeatSingleDayEvent":
//$scope.getEventNames(false, initIdx, eventTypeId);
eventName = $scope.selectedGalaxyEventName != null
? $scope.selectedGalaxyEventName.EventName
: "";
$scope.getEventDatesOnly(false, initIdx, eventName);
eventDate = $scope.selectedGalaxyEventDates != null
? $scope.selectedGalaxyEventDates.EventDate
: "";
$scope.GalaxyEventIdsAndDates = $scope.initial;
$("#GalaxyEventIdDdl").hide();
break;
case "SingleTimedEvent":
//$scope.getEventNames(false, initIdx, eventTypeId);
eventName = $scope.selectedGalaxyEventName != null
? $scope.selectedGalaxyEventName.EventName
: "";
$scope.getEventIdsAndDates(false, initIdx, eventName);
eventId = $scope.selectedGalaxyEventId != null
? $scope.selectedGalaxyEventId.EventId
: "";
eventDate = $scope.selectedGalaxyEventDates != null
? $scope.selectedGalaxyEventDates.EventDate
: "";
$scope.GalaxyEventDates = $scope.initial;
$("#GalaxyEventDatesDdl").hide();
break;
}
$scope.updateModelValue(
typeOfEvent,
eventTypeId,
eventName,
eventId,
eventDate
);
};
$scope.eventTypeIDSelected = function (selectedEventTypeId) {
console.log("Event Type ID selected");
//triggered when EventTypeId dropdown is changed. update the datatype value & provide names in name dropdown
var initIdx = -1;
$scope.getEventNames(false, initIdx, selectedEventTypeId.EventTypeId);
$scope.GalaxyEventIdsAndDates = $scope.initial;// NOT WORKING TO WIPE THE LIST...WHY?
$scope.GalaxyEventDates = $scope.initial; // NOT WORKING TO WIPE THE LIST...WHY?
$scope.updateModelValue(
$scope.selectedTypeOfEvent,
selectedEventTypeId.EventTypeId,
"",
"",
"");
};
$scope.eventNameSelected = function (selectedName) {
//triggered when eventName dropdown is changed. update the datatype value & provide dates and ids in dropdowns
var initIdx = -1;
$scope.getEventIdsAndDates(false, initIdx, selectedName.EventName);
$scope.getEventDatesOnly(false, initIdx, selectedName.EventName);
$scope.updateModelValue(
$scope.selectedTypeOfEvent,
$scope.selectedGalaxyEventTypeId.EventTypeId,
selectedName.EventName,
"",
"");
};
$scope.eventIdSelected = function (selectedEventId) {
//triggered when eventId dropdown is changed. update the datatype value & init date dropdown
var initIdx = -1;
$scope.getEventDatesOnly(false, initIdx, $scope.selectedGalaxyEventName.EventName);
$scope.updateModelValue(
$scope.selectedTypeOfEvent,
$scope.selectedGalaxyEventTypeId.EventTypeId,
$scope.selectedGalaxyEventName.EventName,
selectedEventId.EventId,
selectedEventId.EventDate);
};
$scope.eventDatesSelected = function (selectedEventDate) {
//triggered when eventDate dropdown is changed. update the datatype value & init Id dropdown
var initIdx = -1;
$scope.getEventIdsAndDates(false, initIdx, $scope.selectedGalaxyEventName.EventName);
$scope.updateModelValue(
$scope.selectedTypeOfEvent,
$scope.selectedGalaxyEventTypeId.EventTypeId,
$scope.selectedGalaxyEventName.EventName,
"",
selectedEventDate.EventDate);
};
$scope.getEventTypeIds = function (initVal, idx) {
GalaxyEventSelectorResource.getEventIds().then(function (eventTypeIds) {
$scope.GalaxyEventTypes = eventTypeIds.data;
console.log("successfully retrieved galaxyeventids");
//console.log("Event Type IDs:", eventTypeIds.data[0]);
if (initVal) {
$scope.GalaxyEventTypes.some(function (x, i) {
if (x.EventTypeId == $scope.previousSelectedEventTypeId) {
idx = i;
return true;
}
});
}
$scope.selectedGalaxyEventTypeId = $scope.GalaxyEventTypes[idx];
},
function (data) {
console.log("failed to retrieve galaxyeventids");
});
};
$scope.getEventNames = function (initVal, idx, eventTypeId) {
GalaxyEventSelectorResource.getEventNamesByEventId(eventTypeId).then(function (eventNames) {
$scope.GalaxyEventNames = eventNames.data;
console.log("successfully retrieved galaxyeventnames");
if (initVal) {
$scope.GalaxyEventNames.some(function (x, i) {
if (x.EventName == $scope.previousSelectedEventName) {
idx = i;
return true;
}
});
}
$scope.selectedGalaxyEventName = $scope.GalaxyEventNames[idx];
},
function (data) {
console.log("failed to retrieve galaxyeventnames");
});
};
$scope.getEventIdsAndDates = function(initVal, idx, eventName) {
GalaxyEventSelectorResource.getEventIdsAndDatesByEventName(eventName).then(function (eventIds) {
$scope.GalaxyEventIdsAndDates = eventIds.data;
console.log("successfully retrieved galaxyIdsanddates");
if (initVal) {
$scope.GalaxyEventIdsAndDates.some(function(x, i) {
if (x.EventId == $scope.previousSelectedEventId) {
idx = i;
return true;
}
});
}
$scope.selectedGalaxyEventId = $scope.GalaxyEventIdsAndDates[idx];
},
function(data) {
console.log("failed to retrieve galaxyIdsanddates");
});
};
$scope.getEventDatesOnly = function (initVal, idx, eventName) {
GalaxyEventSelectorResource.getEventDatesByEventName(eventName).then(function (eventDates) {
$scope.GalaxyEventDates = eventDates.data;
console.log("successfully retrieved galaxydates");
if (initVal) {
$scope.GalaxyEventDates.some(function (x, i) {
if (x.EventDate == $scope.previousSelectedEventDate) {
idx = i;
return true;
}
});
}
$scope.selectedGalaxyEventDates = $scope.GalaxyEventDates[idx];
},
function (data) {
console.log("failed to retrieve galaxydates");
});
};
EventSelector.html
<div ng-controller="Our.GalaxyEventSelectorController">
<h5>Select Type of Event</h5>
<!--<div>-->
<div ng-repeat="n in ETypeRadio">
<!-- need to use ng-click as an ng-change on an ng-repeat element does not work -->
<!-- <input type="radio" ng-model="selectedTypeOfEvent" name="tOfE" ng-click="typeOfEventRadioSelected(selectedTypeOfEvent)" ng-value="{{n}}" value="{{n}}" />{{n}}-->
<input type="radio" ng-model="selectedTypeOfEvent" name="tOfE" ng-click="typeOfEventRadioSelected(selectedTypeOfEvent)" ng-value="{{n}}" value="{{n}}" />{{n}}
</div>
<!--</div>-->
<h5>Galaxy Event Type</h5>
<select ng-model="selectedGalaxyEventTypeId" ng-change="eventTypeIDSelected(selectedGalaxyEventTypeId)" ng-options="eventType.EventTypeId + ' - ' + eventType.EventTypeIdDescription for eventType in GalaxyEventTypes track by eventType.EventTypeId"></select>
<br/>
<div id="GalaxyEventNameDdl">
<h5>Galaxy Event Name</h5>
<select ng-model="selectedGalaxyEventName" ng-change="eventNameSelected(selectedGalaxyEventName)" ng-options="name.EventName for name in GalaxyEventNames">
<option value=""> --- Select Event Name ---</option>
</select>
<br />
</div>
<div id="GalaxyEventIdDdl">
<h5>Galaxy Event Id</h5>
<select data-ng-model="selectedGalaxyEventId" ng-change="eventIdSelected(selectedGalaxyEventId)" ng-options="id.EventId + ' - ' + id.EventDate for id in GalaxyEventIdsAndDates track by id.EventId">
<option value=""></option>
</select>
<br />
</div>
<div id="GalaxyEventDatesDdl">
<h5>Galaxy Event Date</h5>
<select data-ng-model="selectedGalaxyEventDates" ng-change="eventDatesSelected(selectedGalaxyEventDates)" ng-options="date.EventDate for date in GalaxyEventDates">
<option value=""></option>
</select>
</div>
We have a .resource.js but this is just performing gets to load our original data from our service.
angular.module("umbraco.resources").factory("GalaxyEventSelectorResource", function ($http) {
var galaxyEventService = {};
galaxyEventService.getEventIds = function () {
return $http.get("/umbraco/backoffice/api/GalaxyEventSelector/GetAllEventTypeIDs");
};
galaxyEventService.getEventById = function (id, propertyType) {
return $http.get("/umbraco/backoffice/api/GalaxyEventSelector/GetEventById?id=" + id + "&propertyType=" + propertyType);
};
galaxyEventService.getEventNamesByEventId = function(eventId) {
return $http.get("/umbraco/backoffice/api/GalaxyEventSelector/GetEventNamesByEventId?eventId=" + eventId);
};
galaxyEventService.getEventIdsAndDatesByEventName = function(eventName) {
return $http.get("/umbraco/backoffice/api/GalaxyEventSelector/GetEventIdsAndDatesByEventName?eventName=" + eventName);
};
galaxyEventService.getEventDatesByEventName = function(eventName) {
return $http.get("/umbraco/backoffice/api/GalaxyEventSelector/GetEventDatesByEventName?eventName=" + eventName);
};

ui-select multiselect is very slow in displaying the choices

I ran into this problem, and I don't know how to solve it. I have used a ui-select multiselect in my page. First, a http.get request is made to a url which gets the data, then the ui-select choices are populated. The data is big - the length of the data is 2100. This data is to be shown as choices. (The data is fetched at the beginning during the loading of the page and is stored in an array)
But the problem is each time I click on the multiselect to select a choice, it takes 4-5 seconds to populate the list and the page becomes very slow. What do I do to reduce this time?
The choices data is stored in an array, the datatype is array of strings.
<ui-select multiple ng-model="selectedFields.name" style="width: 100%;">
<ui-select-match placeholder="Select fields...">{{$item}}</ui-select-match>
<ui-select-choices repeat="fields in availableFields | filter:$select.search">
{{fields}}
</ui-select-choices>
</ui-select>
in the controller,
$scope.selectedFields = {};
$scope.selectedFields.name = [];
$scope.init = function() {
$http.get(url)
.success( function(response, status, headers, config) {
availableFields = response;
})
.error( function(err) {
});
};
$scope.init();
If not this way, is there any other options/choice I can work with which doesn't delay showing the select-choices?
This is a known issue in ui-select. I tried the following ways, both work
1) There is a workaround for this - use
| limitTo: 100
This limits the choice display to 100 but all the choices can be selected. Look at this thread for more details.
2) Since some of the time, there is a need to display the entire list in the choices, 1) is not a viable option. I used a different library - selectize.js. Here's a plunker demo given in the page
Here is complete solution that decorates uiSelectChoices directive.
Items are populated progressively as the user scrolls.
Also takes care of searches in the scrolls.
Also works for all values of position={auto, up, down}
Example
<ui-select-choices
position="up"
all-choices="ctrl.allTenThousandItems"
refresh-delay="0"
repeat="person in $select.pageOptions.people | propsFilter: {name: $select.search, age: $select.search} ">
<div ng-bind-html="person.name | highlight: $select.search"></div>
<small>
email: {{person.email}}
age: <span ng-bind-html="''+person.age | highlight: $select.search"></span>
</small>
</ui-select-choices>
Working Plnkr
Also with With v0.19.5
The directive
app.directive('uiSelectChoices', ['$timeout', '$parse', '$compile', '$document', '$filter', function($timeout, $parse, $compile, $document, $filter) {
return function(scope, elm, attr) {
var raw = elm[0];
var scrollCompleted = true;
if (!attr.allChoices) {
throw new Error('ief:ui-select: Attribute all-choices is required in ui-select-choices so that we can handle pagination.');
}
scope.pagingOptions = {
allOptions: scope.$eval(attr.allChoices)
};
attr.refresh = 'addMoreItems()';
var refreshCallBack = $parse(attr.refresh);
elm.bind('scroll', function(event) {
var remainingHeight = raw.offsetHeight - raw.scrollHeight;
var scrollTop = raw.scrollTop;
var percent = Math.abs((scrollTop / remainingHeight) * 100);
if (percent >= 80) {
if (scrollCompleted) {
scrollCompleted = false;
event.preventDefault();
event.stopPropagation();
var callback = function() {
scope.addingMore = true;
refreshCallBack(scope, {
$event: event
});
scrollCompleted = true;
};
$timeout(callback, 100);
}
}
});
var closeDestroyer = scope.$on('uis:close', function() {
var pagingOptions = scope.$select.pagingOptions || {};
pagingOptions.filteredItems = undefined;
pagingOptions.page = 0;
});
scope.addMoreItems = function(doneCalBack) {
console.log('new addMoreItems');
var $select = scope.$select;
var allItems = scope.pagingOptions.allOptions;
var moreItems = [];
var itemsThreshold = 100;
var search = $select.search;
var pagingOptions = $select.pagingOptions = $select.pagingOptions || {
page: 0,
pageSize: 20,
items: $select.items
};
if (pagingOptions.page === 0) {
pagingOptions.items.length = 0;
}
if (!pagingOptions.originalAllItems) {
pagingOptions.originalAllItems = scope.pagingOptions.allOptions;
}
console.log('search term=' + search);
console.log('prev search term=' + pagingOptions.prevSearch);
var searchDidNotChange = search && pagingOptions.prevSearch && search == pagingOptions.prevSearch;
console.log('isSearchChanged=' + searchDidNotChange);
if (pagingOptions.filteredItems && searchDidNotChange) {
allItems = pagingOptions.filteredItems;
}
pagingOptions.prevSearch = search;
if (search && search.length > 0 && pagingOptions.items.length < allItems.length && !searchDidNotChange) {
//search
if (!pagingOptions.filteredItems) {
//console.log('previous ' + pagingOptions.filteredItems);
}
pagingOptions.filteredItems = undefined;
moreItems = $filter('filter')(pagingOptions.originalAllItems, search);
//if filtered items are too many scrolling should occur for filtered items
if (moreItems.length > itemsThreshold) {
if (!pagingOptions.filteredItems) {
pagingOptions.page = 0;
pagingOptions.items.length = 0;
} else {
}
pagingOptions.page = 0;
pagingOptions.items.length = 0;
allItems = pagingOptions.filteredItems = moreItems;
} else {
allItems = moreItems;
pagingOptions.items.length = 0;
pagingOptions.filteredItems = undefined;
}
} else {
console.log('plain paging');
}
pagingOptions.page++;
if (pagingOptions.page * pagingOptions.pageSize < allItems.length) {
moreItems = allItems.slice(pagingOptions.items.length, pagingOptions.page * pagingOptions.pageSize);
}
for (var k = 0; k < moreItems.length; k++) {
pagingOptions.items.push(moreItems[k]);
}
scope.calculateDropdownPos();
scope.$broadcast('uis:refresh');
if (doneCalBack) doneCalBack();
};
scope.$on('$destroy', function() {
elm.off('scroll');
closeDestroyer();
});
};
}]);
As stated, ui-select is having quite a few performance issues, but there is a workaround for the limit issue.
If you follow akashrajkn's approach then you will notice that it will actually cut out important pieces of data because it will only render 100 at a time. There is a fix that has passed the unit tests and it can be found on the thread here:
https://github.com/angular-ui/ui-select/pull/716
Basically, if you are storing the javascript file locally, then you can adjust the unminified version. All you need to do is implement the changes he made in the pull request and it should help out significantly. In order to apply the limiting factor, take a look at the below, modified example:
<ui-select multiple ng-model="selectedFields.name" limit = "10" style="width: 100%;">
<ui-select-match placeholder="Select fields...">{{$item}}</ui-select-match>
<ui-select-choices repeat="fields in availableFields | filter:$select.search | limitTo:$select.limit ">
{{fields}}
</ui-select-choices>
</ui-select>
The above will limit your data in the drop down while also maintaining the level of consistency needed.
Because I cannot leave a comment (not enough rep) I write this as an answer and I am sorry it is no answer for the problem.
#bhantol I changed the following line of code to your solution which is working perfectly for me so far
for (var k = 0; k < moreItems.length; k++) {
pagingOptions.items.push(moreItems[k]);
}
for (var k = 0; k < moreItems.length; k++) {
if (pagingOptions.items.indexOf(moreItems[k]) == -1){
pagingOptions.items.push(moreItems[k]);
}
}
This prevents duplicated items from showing up if the user is starting to write a filter and then deletes it.
Also I just figured out that if the list is smaller than 20 items it will not work so I changed:
if (pagingOptions.page * pagingOptions.pageSize < allItems.length) {
moreItems = allItems.slice(pagingOptions.items.length, pagingOptions.page * pagingOptions.pageSize);
}
to:
if (pagingOptions.page * pagingOptions.pageSize < allItems.length) {
moreItems = allItems.slice(pagingOptions.items.length, pagingOptions.page * pagingOptions.pageSize);
}
else{ moreItems = allItems;}
Maybe this will help you somehow and sorry again for not answering the question.

Filter by multiple columns with ng-repeat

I'm wondering if there's an easy way in Angular to filter a table using ng-repeat on specific columns using or logic, rather than and. Right now, my filter is searching everything in the table (10+ columns of data), when it really only needs to filter on 2 columns of data (ID and Name).
I've managed to get it down to look only at those 2 columns when filtering (by using an object in the filter expression as per the docs and looking at this SO answer), but it's using and logic, which is too specific. I'd like to get it to use or logic, but am having trouble.
My HTML
<input type="text" ng-model="filterText" />
<table>
<tr ng-repeat="item in data"><td>{{ item.id }}</td><td>{{ item.name }}</td>...</tr>
</table>
My filter logic:
$filter('filter')(data, {id:$scope.filterText, name:$scope.filterText})
The filtering works, but again, it's taking the intersection of the matching columns rather than the union. Thanks!
It's not hard to create a custom filter which allows you to have as many arguments as you want. Below is an example of a filter with one and two arguments, but you can add as many as you need.
Example JS:
var app = angular.module('myApp',[]);
app.filter('myTableFilter', function(){
// Just add arguments to your HTML separated by :
// And add them as parameters here, for example:
// return function(dataArray, searchTerm, argumentTwo, argumentThree) {
return function(dataArray, searchTerm) {
// If no array is given, exit.
if (!dataArray) {
return;
}
// If no search term exists, return the array unfiltered.
else if (!searchTerm) {
return dataArray;
}
// Otherwise, continue.
else {
// Convert filter text to lower case.
var term = searchTerm.toLowerCase();
// Return the array and filter it by looking for any occurrences of the search term in each items id or name.
return dataArray.filter(function(item){
var termInId = item.id.toLowerCase().indexOf(term) > -1;
var termInName = item.name.toLowerCase().indexOf(term) > -1;
return termInId || termInName;
});
}
}
});
Then in your HTML:
<tr ng-repeat="item in data | myTableFilter:filterText">
Or if you want to use multiple arguments:
<tr ng-repeat="item in data | myTableFilter:filterText:argumentTwo:argumentThree">
Use this to search on All Columns (can be slow): search.$
AngularJS API: filter
Any Column Search:
<input ng-model="search.$">
<table>
<tr ng-repeat="friendObj in friends | filter:search:strict">
...
To expand on the excellent answer by #charlietfl, here's a custom filter that filters by one column(property) which is passed to the function dynamically instead of being hard-coded. This would allow you to use the filter in different tables.
var app=angular.module('myApp',[]);
app.filter('filterByProperty', function () {
/* array is first argument, each addiitonal argument is prefixed by a ":" in filter markup*/
return function (dataArray, searchTerm, propertyName) {
if (!dataArray) return;
/* when term is cleared, return full array*/
if (!searchTerm) {
return dataArray
} else {
/* otherwise filter the array */
var term = searchTerm.toLowerCase();
return dataArray.filter(function (item) {
return item[propertyName].toLowerCase().indexOf(term) > -1;
});
}
}
});
Now on the mark-up side
<input type="text" ng-model="filterText" />
<table>
<tr ng-repeat="item in data |filterByProperty:filterText:'name'"><td>{{ item.id }}</td><td>{{ item.name }}</td>...</tr>
</table>
I figured it out- I had to write my own custom filter. Here is my solution:
var filteredData;
filteredData = $filter('filter')(data, function(data) {
if ($scope.filter) {
return data.id.toString().indexOf($scope.filter) > -1 || data.name.toString().indexOf($scope.filter) > -1;
} else {
return true;
}
});
I created this filter to perform search in several fields:
var find = function () {
return function (items,array) {
var model = array.model;
var fields = array.fields;
var clearOnEmpty = array.clearOnEmpty || false;
var filtered = [];
var inFields = function(row,query) {
var finded = false;
for ( var i in fields ) {
var field = row[fields[i]];
if ( field != undefined ) {
finded = angular.lowercase(row[fields[i]]).indexOf(query || '') !== -1;
}
if ( finded ) break;
}
return finded;
};
if ( clearOnEmpty && model == "" ) return filtered;
for (var i in items) {
var row = items[i];
var query = angular.lowercase(model);
if (query.indexOf(" ") > 0) {
var query_array = query.split(" ");
var x;
for (x in query_array) {
query = query_array[x];
var search_result = true;
if ( !inFields(row,query) ) {
search_result = false;
break;
}
}
} else {
search_result = inFields(row,query);
}
if ( search_result ) {
filtered.push(row);
}
}
return filtered;
};
};
How to use:
<tr repeat="item in colletion
| find: {
model : model, // Input model
fields : [ // Array of fields to filter
'FIELD1',
'FIELD2',
'FIELD3'
],
clearOnEmpty: true // Clear rows on empty model (not obligatory)
} "></tr>
Easily We can do this type Following written code according you will easily create another field filter....
var myApp = angular.module('myApp',[]);
myApp.filter('myfilter',myfilter);
function myfilter(){
return function (items, filters) {
if (filters == null) {
return items;
}
var filtered = [];
//Apply filter
angular.forEach(items, function (item) {
if ((filters.Name == '' || angular.lowercase(item.Name).indexOf(angular.lowercase(filters.Name)) >= 0)
)
{
filtered.push(item);
}
});
return filtered;
};
}
myApp.controller('mycontroller',['$scope',function($scope){
$scope.filters={Name:'',MathsMarks:''};
$scope.students=[];
var i=0;
for(i=0;i<5;i++){
var item={Name:'',Marks:[]};
item.Name='student' + i;
item.Marks.push({Maths:50-i,Science:50 +i});
$scope.students.push(item);
}
}]);
<html ng-app='myApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
</head>
<body ng-controller='mycontroller'>
<input type='text' name='studentName' ng-model="filters.Name" placeholder='Enter Student Name'>
<div ng-repeat="student in students | myfilter: filters">
Name : {{student.Name}} Marks == >
<span ng-repeat="m in student.Marks">Maths:{{m.Maths}} Science:{{m.Science}}</span>
</div>
</body>
</html>
Here is my solution, it's very lazy, it will search on all strings in array on first level, you could update this to recusively go down the tree, but this should be good enough...
app.filter('filterAll', function () {
return function (dataArray, searchTerm, propertyNames) {
if (!dataArray) return;
if (!searchTerm) {
return dataArray;
} else {
if (propertyNames == undefined) {
propertyNames = [];
for (var property in dataArray[0]) {
if(typeof dataArray[0][property] == "string" &&
property != "$$hashKey" &&
property != "UnitName" )
propertyNames.push(property);
}
}
console.log("propertyNames", propertyNames);
var term = searchTerm.toLowerCase();
return dataArray.filter(function (item) {
var found = false;
propertyNames.forEach(function(val) {
if (!found) {
if (item[val] != null && item[val].toLowerCase().indexOf(term) > -1)
found = true;
}
});
return found;
});
}
}
});
see this link Filter multiple object properties together in AngularJS

How to make ng-repeat filter out duplicate results

I'm running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only about 6 categories.
My current code is this:
<select ng-model="orderProp" >
<option ng-repeat="place in places" value="{{place.category}}">{{place.category}}</option>
</select>
The output is 100 different options, mostly duplicates. How do I use Angular to check whether a {{place.category}} already exists, and not create an option if it's already there?
edit: In my javascript, $scope.places = JSON data, just to clarify
You could use the unique filter from AngularUI (source code available here: AngularUI unique filter) and use it directly in the ng-options (or ng-repeat).
<select ng-model="orderProp" ng-options="place.category for place in places | unique:'category'">
<option value="0">Default</option>
// unique options from the categories
</select>
Or you can write your own filter using lodash.
app.filter('unique', function() {
return function (arr, field) {
return _.uniq(arr, function(a) { return a[field]; });
};
});
You can use 'unique'(aliases: uniq) filter in angular.filter module
usage: colection | uniq: 'property'
you can also filter by nested properties: colection | uniq: 'property.nested_property'
What you can do, is something like that..
function MainController ($scope) {
$scope.orders = [
{ id:1, customer: { name: 'foo', id: 10 } },
{ id:2, customer: { name: 'bar', id: 20 } },
{ id:3, customer: { name: 'foo', id: 10 } },
{ id:4, customer: { name: 'bar', id: 20 } },
{ id:5, customer: { name: 'baz', id: 30 } },
];
}
HTML: We filter by customer id, i.e remove duplicate customers
<th>Customer list: </th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
<td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>
result
Customer list:
foo 10
bar 20
baz 30
this code works for me.
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})
and then
var colors=$filter('unique')(items,"color");
If you want to list categories, I think you should explicitly state your
intention in the view.
<select ng-model="orderProp" >
<option ng-repeat="category in categories"
value="{{category}}">
{{category}}
</option>
</select>
in the controller:
$scope.categories = $scope.places.reduce(function(sum, place) {
if (sum.indexOf( place.category ) < 0) sum.push( place.category );
return sum;
}, []);
Here's a straightforward and generic example.
The filter:
sampleApp.filter('unique', function() {
// Take in the collection and which field
// should be unique
// We assume an array of objects here
// NOTE: We are skipping any object which
// contains a duplicated value for that
// particular key. Make sure this is what
// you want!
return function (arr, targetField) {
var values = [],
i,
unique,
l = arr.length,
results = [],
obj;
// Iterate over all objects in the array
// and collect all unique values
for( i = 0; i < arr.length; i++ ) {
obj = arr[i];
// check for uniqueness
unique = true;
for( v = 0; v < values.length; v++ ){
if( obj[targetField] == values[v] ){
unique = false;
}
}
// If this is indeed unique, add its
// value to our values and push
// it onto the returned array
if( unique ){
values.push( obj[targetField] );
results.push( obj );
}
}
return results;
};
})
The markup:
<div ng-repeat = "item in items | unique:'name'">
{{ item.name }}
</div>
<script src="your/filters.js"></script>
I decided to extend #thethakuri's answer to allow any depth for the unique member. Here's the code. This is for those who don't want to include the entire AngularUI module just for this functionality. If you're already using AngularUI, ignore this answer:
app.filter('unique', function() {
return function(collection, primaryKey) { //no need for secondary key
var output = [],
keys = [];
var splitKeys = primaryKey.split('.'); //split by period
angular.forEach(collection, function(item) {
var key = {};
angular.copy(item, key);
for(var i=0; i<splitKeys.length; i++){
key = key[splitKeys[i]]; //the beauty of loosely typed js :)
}
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
Example
<div ng-repeat="item in items | unique : 'subitem.subitem.subitem.value'"></div>
I had an array of strings, not objects and i used this approach:
ng-repeat="name in names | unique"
with this filter:
angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
};
if(arry === undefined || arry.length === 0){
return '';
}
else {
return arry.getUnique();
}
};
}
UPDATE
I was recomending the use of Set but sorry this doesn't work for ng-repeat, nor Map since ng-repeat only works with array. So ignore this answer. anyways if you need to filter out duplicates one way is as other has said using angular filters, here is the link for it to the getting started section.
Old answer
Yo can use the ECMAScript 2015 (ES6) standard Set Data structure, instead of an Array Data Structure this way you filter repeated values when adding to the Set. (Remember sets don't allow repeated values). Really easy to use:
var mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add("some text");
var o = {a: 1, b: 2};
mySet.add(o);
mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5); // true
mySet.has(Math.sqrt(25)); // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true
mySet.size; // 4
mySet.delete(5); // removes 5 from the set
mySet.has(5); // false, 5 has been removed
mySet.size; // 3, we just removed one value
It seems everybody is throwing their own version of the unique filter into the ring, so I'll do the same. Critique is very welcome.
angular.module('myFilters', [])
.filter('unique', function () {
return function (items, attr) {
var seen = {};
return items.filter(function (item) {
return (angular.isUndefined(attr) || !item.hasOwnProperty(attr))
? true
: seen[item[attr]] = !seen[item[attr]];
});
};
});
Here's a template-only way to do it (it's not maintaining the order, though). Plus, the result will be ordered as well, which is useful in most cases:
<select ng-model="orderProp" >
<option ng-repeat="place in places | orderBy:'category' as sortedPlaces" data-ng-if="sortedPlaces[$index-1].category != place.category" value="{{place.category}}">
{{place.category}}
</option>
</select>
None of the above filters fixed my issue so I had to copy the filter from official github doc. And then use it as explained in the above answers
angular.module('yourAppNameHere').filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
If you want to get unique data based on the nested key:
app.filter('unique', function() {
return function(collection, primaryKey, secondaryKey) { //optional secondary key
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key;
secondaryKey === undefined ? key = item[primaryKey] : key = item[primaryKey][secondaryKey];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
Call it like this :
<div ng-repeat="notify in notifications | unique: 'firstlevel':'secondlevel'">
Add this filter:
app.filter('unique', function () {
return function ( collection, keyname) {
var output = [],
keys = []
found = [];
if (!keyname) {
angular.forEach(collection, function (row) {
var is_found = false;
angular.forEach(found, function (foundRow) {
if (foundRow == row) {
is_found = true;
}
});
if (is_found) { return; }
found.push(row);
output.push(row);
});
}
else {
angular.forEach(collection, function (row) {
var item = row[keyname];
if (item === null || item === undefined) return;
if (keys.indexOf(item) === -1) {
keys.push(item);
output.push(row);
}
});
}
return output;
};
});
Update your markup:
<select ng-model="orderProp" >
<option ng-repeat="place in places | unique" value="{{place.category}}">{{place.category}}</option>
</select>
This might be overkill, but it works for me.
Array.prototype.contains = function (item, prop) {
var arr = this.valueOf();
if (prop == undefined || prop == null) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
return true;
}
}
}
else {
for (var i = 0; i < arr.length; i++) {
if (arr[i][prop] == item) return true;
}
}
return false;
}
Array.prototype.distinct = function (prop) {
var arr = this.valueOf();
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (!ret.contains(arr[i][prop], prop)) {
ret.push(arr[i]);
}
}
arr = [];
arr = ret;
return arr;
}
The distinct function depends on the contains function defined above. It can be called as array.distinct(prop); where prop is the property you want to be distinct.
So you could just say $scope.places.distinct("category");
Create your own array.
<select name="cmpPro" ng-model="test3.Product" ng-options="q for q in productArray track by q">
<option value="" >Plans</option>
</select>
productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
var index = $scope.productArray.indexOf(value.Product);
if(index === -1)
{
$scope.productArray.push(value.Product);
}
});

Resources