How to optimize the performance of ng-repeat in AngularJS?

Today we would focus on improving the performance of Angular JS code by learning the basics of ng-repeat and then how to enhance its capabilities.

Follow us for more learning Fb,G+,Twitter.

ng-repeat :- 
It is directive which create instant of template for each item in the collection. It is identical to looping concept in any language say Java, for example we need to display all the items in an array we would use “ForEach item in items” in Java. Similarly we would say “ng-repeat = item in items” in Angular JS terms. 

Note:- We have angular.forEach function available in AngularJs used for iteration.

Example:- 
We need to display all the name-version pairs on the view.We would implement ng-repeat as we did inthe following example…

ng-repeat example code


Live Demo

Note:-By default, ngRepeat does not allow duplicate items in arrays. We can overcome this by defining our own track by expression. 
Example below we have key = Angular is repeating twice but still in the output we are getting the one key-value pair.

Duplicate key in ng-repeat



How many watches does ng-repeat create for above example?
We knew that Angular creates a $watch for every single ng directive, so above list has 3 + 1 watches (3 names + 1 for ng-directive).Imagine if we have huge array of names how many watches would be created.

How to improve the performance of ng-repeat?

1. Using track by:-
Track by assist Angular in recognizing unique items. Now by default for every item that is getting displayed using ng-repeat, AngularJS calculates hash value to uniquely identify the object. To make sure that whether it has an object before or new object need to be created to display it.

Suppose we are fetching our name-version array in above example on frequent basis this means reference to objects displayed changes multiple times in ng-repeat.So it is recommended to tell AngularJS, how it can identify the unique items. 

Our solution is track by.
“ng-repeat =”name in items track by name.id”

This tells AngularJS that each name is uniquely identified by the name.id value, and to reuse DOM elements as long as the id field does not change.Thus we have used our own key for ng-repeat to identify the objects, instead of generating the unique ID’s each time.

Learning: – implement track by to get unique values

2.Using filters in controller rather than directly in HTML
Filter helps in limiting our data by giving data in user required form, for example we want our version above  to have 2 decimal places at end so we can just change the code as

ng-repeat = “” | filter =limitto:2

But this becomes a headache and a performance issue incase we are filtering the data in the HTML. Better  optimize the triggering of filer in our controller rather than implementing it directly in HTML.

Learning: – Limit DOM filters

3. One-time data binding {{::expression}}

It can be done by simply using the prefix “::”( double colon) before the angular expression.

It helps as AngularJS stops watching the variable and updating it in the UI. So resources are freed for watchlist thus improving the performance.
Remember this approach is useful useful for data that is not expected to change after displayed to the user.

Learning: – Implement bind-once approach if possible

Learn more Angular Concepts

Best and affordable editor for writing visual Basic code??

What is your favorite VBS editor to write scripts?

If we search vb editor on Google you would find thousand of suggestions like notepad++,vbsedit and many more fancy IDE.But sometimes there are situations, like due to organization compliance policies or some other reasons, that we don’t have access to these editors .Then what to do in that case of scenarios.

“Don’t use a lot where a little will do.” -Proverb

Thus we have to achieve maximum out of what we have.

Solution is utilizing the inbuilt feature of developer tab  in  Microsoft excel to code our vbs/vba scripts.

We thought of sharing the same with you all, follow us on  Fb,G+,Twitter for more updates. 

Steps:-

1. Open excel instance.

2. Look for “Developer tab” -> Visual Basic

Opening Visual Basic editor in Excel
Note: – Incase “Developer tab” is not available in the excel ribbon, then, click on Microsoft icon on the top left corner of excel ->Excel Options -> Popular -> check the “Show Developer tab in the ribbon” > OK
We can directly launch Visual basic IDE by using ALT+ F11,after launching the excel instance.

3. Right click on VBA project in the “project explorer “ -> Insert -> module

Inserting Module in Excel

4. Now we ready to write our code, it provides intellisense and debugging 

Debug in VBA project Excel


facilities(like we have watch option in UFT same is available here) 

5. Save as type “Excel Macro-Enabled Workbook”

6. Run (F5) or green play icon on the ribbon panel.
Explore the other features on the panel to learn more.

Run VBA project Excel

Please share your views or your comments about what can be your favorite editor incase you have limited resources, other than Notepad offcourse 🙂

Learn Vbscript
Selenium

Example scenarios for working with Dictionary Object Using vbscript.

Every day you wake up is a victory. Learn more and share more….

Concept 1:-How to find the occurrence count of item in a given sample?

Sorting using Dictionary object


Using dictionary object we would find the count of occurrence of given value in the sample.
Example: – we need to find the “Help” words in the given string say: – “God help those who help themselves”

Lets connect for more updates at  Fb,G+,Twitter.
Code:-

'Input String
sSample = "God help those who help themselves"
'Splitting the given string
arrSample = Split(sSample)
'Calling the function to get the Count of all the items
Set objCount = fn_Count(arrSample)
arrKey = objCount.Keys
For iRun = 0 To objCount.Count - 1
MsgBox "Count of '" & arrKey(iRun) & "' =" & objCount.Item(arrKey(iRun))
Next
'*******************************************Function*********************************
'Function Name:- fn_Count
'Function Description:- Function find the occuerence of given word in the string
'Input Parameters:- Given String
'Output Parameters:- Dictionary object
'************************************************************************************

Function fn_Count(arrSample)
Dim iRow, iItem
Dim objDic
Set objDic = CreateObject("scripting.dictionary")
'Looping through array
For iRow = LBound(arrSample) To UBound(arrSample)
iItem = arrSample(iRow)
If Not objDic.Exists(iItem) Then
objDic.Add iItem, 1
Else
objDic.Item(iItem) = objDic.Item(iItem) + 1
End If
Next

Set fn_Count = objDic
End Function
Concept 2:- How to sort items in the given dictionary?
Note: – we can sort dictionary keys in the same manner as we did items.

Code:-
'*******************************************Function*********************************
'Function Name:- fn_SortDictionary
'Function Description:- Function to sort the items in the given dictionary
'Input Parameters:- Unsorted Dictionary object
'Output Parameters:- Sorted Dictionary object
'************************************************************************************
Function fn_SortDictionary(objdict)
Dim i, j, temp
For Each i In objdict
For Each j In objdict
If (objdict.Item(i) <= objdict.Item(j)) Then
temp = objdict.Item(i)
objdict.Item(i) = objdict.Item(j)
objdict.Item(j) = temp
End If
Next
Next
Set fn_SortDictionary = objdict
End Function
Concept 3:- How to sort dictionary Key-Item pairs based on the Item or key?

This is different from the above concept as we are not simply sorting the items or keys present in the dictionary but actually we are creating a new sorted dictionary. Some time it is required to sort the Key-Value pairs in ascending or descending order.
Note: – Here we are sorting on the basis of items and some time our item values can be repeating.

Code:-
    'Creating dictionary
Dim objDic
Set objDic = CreateObject("scripting.dictionary")
objDic.Add "USD", "80"
objDic.Add "SAG", "55"
objDic.Add "CAD", "80"
objDic.Add "AUD", "50"

'Function call to sort the dictionary
Set objSDic = fn_SortDictionary(objDic)
'Printing the Result of sorted Dictionary in the Msgbox
For i = 0 To objSDic.Count - 1
Txt = Txt & objSDic.keys()(i) & objSDic.items()(i) & vbCrLf
Next i
MsgBox Txt




'*******************************************Function*********************************
'Function Name:- fn_SortDictionary
'Function Description:- Function to sort the Key and item pairs in the given dictionary
'Input Parameters:- Unsorted Dictionary object
'Output Parameters:- Sorted Dictionary object
'************************************************************************************
Function fn_SortDictionary(objIDict)

'Taking the Orginal Keys
arrKey = objIDict.keys
'Taking the count of items values
arrSort = objIDict.items

'We would sort on the basis of Items but for keeping track which item belongs to the key
'we would add index value to the existing items
'Incase we have duplicating items we be still be able to sort.
'Adding index to all the items
For i = LBound(arrSort) To UBound(arrSort)
arrSort(i) = arrSort(i) & ";" & i
Next
'Logic for sorting

For i = LBound(arrSort) To UBound(arrSort) - 1
For j = i + 1 To UBound(arrSort)
'Split the value of arrsort so that we dont consider the index part
arrFSortI = Split(arrSort(i), ";")
arrFSortJ = Split(arrSort(j), ";")
If Cint(arrFSortI(0)) < Cint(arrFSortJ(0)) Then
'Concatenating the split array and joining the Index at the end
Temp = arrFSortJ(0) & ";" & arrFSortJ(1)
arrSort(j) = arrFSortI(0) & ";" & arrFSortI(1)
arrSort(i) = Temp
End If
Next j
Next i
'Creating the Temp Dictionary object
Set TempDict = CreateObject("scripting.Dictionary")
'Adding sorted values to the dictionary
For i = LBound(arrSort) To UBound(arrSort)
KeyIndex = Split(arrSort(i), ";")
TempDict.Add Key:=arrKey(KeyIndex(1)), Item:=KeyIndex(0)
Next i
'Returning the sorted dictionary
Set fn_SortDictionary = TempDict
End Function


SQL Interview Questions(Set-2)

Here comes our next bundle of SQL interview questions. We have also given a brush up for the brief answer hints at the bottom. Hope it help you all in achieving your target job.

Keep sharing and Keep learning.

Do follow us for more updates on  Fb,G+,Twitter.

Learn more and share more
Learn more to achieve more…

  1. What is the difference betweenwhere and having clause?
  2. What is composite key? How it differs from Candidate key?
  3. We have 2 tables A&B. Write a query to get just non matching account ID from B table using joins.
  4. In the above table modify the query to fetch non matching account ID from both the tables(Means removing the common ID’s)
  5. How to remove duplicate values from a Table A.
  6. In question 5? How to delete only one duplicate row from a table for each combination?
  7. We have 2 tables, Candidate (id, name) and vote (id, Count), write a query to give the name of winning candidate?
  8. Write a query to find the nth maximum salary in a emp table
  9. What is a join? Explain the different types of joins?
  10. Explain the sequence of query execution?
Hints:-

1. Where clause cannot be used with aggregate functions (like sum, max, min, count) so we need to implement having clause.
Example for a Table A we need to count the applications where count is greater than 5, so we cannot create a query like select count (applications) from table A where count (app) > 5, we need to use ‘having’ clause select count (app) from Table A having (count (app)) > 5
Note: – We generally use having clause with group by clause but we can use it alone. If the SQL SELECT statement does not contain aggregate functions, here it would act like a Where clause itself.

2. Composite primary key is used to define more than one primary column for a table.
CREATE TABLE A
(ID integer,test
NAME varchar (30),
CLASS varchar (50),
PRIMARY KEY (ID, NAME));
Candidate key: – A Candidate Key can be any column or a combination of columns that can qualify as unique key in database. And there could be multiple Candidate Keys in one table. Each Candidate Key can qualify as Primary Key but we have only one primary key.
Note:-A table can have multiple Candidate Keys that are unique as single column or combined multiple columns to the table. They are all candidates for Primary Key. Candidate keys that follow all the three rules – 1) Not Null, 2) Unique Value in Table and 3) Static – are the best candidates for Primary Key.

3. We need to implement Left outer join on Table B and Table A.Also we used ‘Where’ clause to restrict the common records in both the tables.
SELECT B.Accountid
FROM Table B AS B
LEFT JOIN Table A AS A ON A.ID = B.Accountid
WHERE A.ID IS NULL
Right Outer Join Example


4. This time we would exclude the common ID’s again by using ‘Where’ Clause and “Full Outer Join”
SELECT  B.Accountid, A.ID FROM Table B AS B
FULL OUTER JOIN Table A AS A ON A.ID = B.Accountid
WHERE A.ID IS NULL OR B.AccountID  IS  NULL
Full Outer Join Example


5.  It deletes any of the rows which are repeating from the table.
delete from Table A  where ID in (select  A.ID  from Table  A  group by ID  having
    count (*) >1)

7. We need to use “Inner Join” as we need the common data of both the tables based on the candidate ID.
SELECT  B.CandidateName
FROM Table Candidate AS B
INNER JOIN Table vote AS ON A.ID = B.ID
GROUP BY B.Name
8. SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary
How it works, sub query it finds the N highest salaries in the Employee table and arranges them in descending order.Now,the outer query will actually rearrange those values in ascending order, which is what the very last line “ORDER BY Salary” does, because of the fact that the ORDER BY Default is to sort values in ASCENDING order. Finally, that means the Nth highest salary will be at the top of the list of salaries, which means we just want the first row, which is exactly what “SELECT TOP 1 Salary” will do for us.

9. Join means a guide to database to combine data from more than one table.
Types of join:-
Inner,Outer,Cross&Self Join

Inner Join: – inner join produces a result set that is limited to the rows where there is a match in both tables, thus it sends the matching data from joining tables

Outer types: – Left Outer, Right outer and Full Outer.

Left outer join: – It gives data from the left join table + the common data from the joining tables.

Right outer join: – Reverse of above, data from the right joining table + common data from the joining tables.

Full outer join:-A full outer join, or just outer join, produces a result set with all of the rows of both tables, regardless of whether there are any matches.

Thus full is the combination of left and right outer joins

Cross join: – The row count of the result is equal to the number of rows in the first table times the number of rows in the second table. Each row is a combination of the rows of the first and second table.

Self join: – Joining the same table twice

10 .General sequence of query execution :-

1. FROM
2. ON
3. Joins
4. WHERE
5. GROUP BY
6. HAVING
7. SELECT
8. DISTINCT
9. ORDER BY
10. Aggregate functions



More interview Questions. 
Learn Excel Programming concepts.