Working with Lodash in AngularJS

Loading

Lodash is a powerful JavaScript utility library that provides functional programming helpers for handling arrays, objects, numbers, and strings efficiently. In AngularJS, Lodash can improve performance, simplify data manipulation, and optimize the digest cycle.


1. Installing Lodash in an AngularJS Project

Using a CDN (Recommended)

Add the Lodash script before your AngularJS script in the HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

Using npm or Yarn

If you’re using a module bundler:

npm install lodash --save

or

yarn add lodash

Then, import Lodash in your JavaScript file:

import _ from 'lodash';

2. Injecting Lodash into an AngularJS App

Lodash is available globally as _, but to follow best practices, inject it as a service.

Creating an AngularJS Factory for Lodash

var app = angular.module('myApp', []);

app.factory('_', function() {
return window._; // Exposes Lodash as a service
});

app.controller('MainController', function($scope, _) {
$scope.numbers = [1, 2, 3, 4, 5, 6];
$scope.evenNumbers = _.filter($scope.numbers, function(n) { return n % 2 === 0; });
});

HTML Usage

<div ng-app="myApp" ng-controller="MainController">
<p>Even Numbers: {{ evenNumbers }}</p>
</div>

Output: [2, 4, 6]


3. Working with Lodash in AngularJS Controllers

Filtering Arrays (_.filter)

$scope.users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];

$scope.adults = _.filter($scope.users, function(user) {
return user.age >= 30;
});

Output: [ {name: "Bob", age: 30}, {name: "Charlie", age: 35} ]


Finding Elements (_.find)

$scope.user = _.find($scope.users, { name: "Alice" });

Output: { name: "Alice", age: 25 }


Sorting Arrays (_.orderBy)

$scope.sortedUsers = _.orderBy($scope.users, ['age'], ['desc']);

Output: Users sorted in descending order of age.


Removing Items (_.remove)

$scope.numbers = [1, 2, 3, 4, 5, 6];

_.remove($scope.numbers, function(n) {
return n % 2 === 0; // Remove even numbers
});

Output: [1, 3, 5]


4. Optimizing AngularJS Performance with Lodash

Debouncing User Input (_.debounce)

Prevents unnecessary API calls when the user types quickly in a search box.

$scope.search = _.debounce(function(query) {
console.log("API Call: Searching for " + query);
}, 300);

HTML Usage

<input type="text" ng-model="query" ng-change="search(query)">

Prevents multiple API calls when the user types quickly.


Throttling Function Calls (_.throttle)

Ensures that a function is called at most once every specified interval.

$scope.updateScrollPosition = _.throttle(function() {
console.log("Scroll event processed");
}, 500);
htmlCopyEdit<div onscroll="updateScrollPosition()">
    Scroll here...
</div>

Useful for scroll, resize, or keypress events.


5. Using Lodash for Object Manipulation

Cloning Objects (_.cloneDeep)

$scope.user = { name: "Alice", age: 25 };
$scope.cloneUser = _.cloneDeep($scope.user);

Prevents accidental modifications to the original object.


Merging Objects (_.merge)

$scope.user1 = { name: "Alice", age: 25 };
$scope.user2 = { age: 30, city: "New York" };

$scope.mergedUser = _.merge({}, $scope.user1, $scope.user2);

Output: { name: "Alice", age: 30, city: "New York" }


Picking Specific Properties (_.pick)

$scope.user = { name: "Alice", age: 25, city: "NYC" };
$scope.userBasic = _.pick($scope.user, ['name', 'city']);

Output: { name: "Alice", city: "NYC" }


6. Lodash with AngularJS $watch

Lodash can be used to prevent unnecessary digest cycle executions.

Using _.debounce in $watch

$scope.$watch('searchQuery', _.debounce(function(newVal) {
console.log("Searching for: " + newVal);
}, 300));

Prevents multiple function calls when a user types continuously.


Using _.isEqual to Optimize Watch Performance

$scope.$watch('user', function(newVal, oldVal) {
if (!_.isEqual(newVal, oldVal)) {
console.log("User data changed");
}
}, true);

Prevents unnecessary updates when object reference remains the same.


7. Lodash Utilities for AngularJS

Checking if a Variable is Empty (_.isEmpty)

$scope.isEmptyArray = _.isEmpty([]); // true
$scope.isEmptyObject = _.isEmpty({}); // true

Generating a Random Number (_.random)

$scope.randomNumber = _.random(1, 100);

Creating Unique IDs (_.uniqueId)

$scope.userId = _.uniqueId('user_');

Output: "user_1", "user_2", etc.

Leave a Reply

Your email address will not be published. Required fields are marked *