Wednesday 5 April 2017

How would you make an Angular service return a promise? Write a code snippet as an example

To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:

angular.factory('testService', function($q){ return { getName: function(){ var deferred = $q.defer(); //API call here that returns data testAPI.getName().then(function(name){ deferred.resolve(name) }) return deferred.promise; } } })

What makes the angular.copy() method so powerful in angular js?

It creates a deep copy of the variable.

A deep copy of a variable means it doesn’t point to the same memory reference as that variable. Usually assigning one variable to another creates a “shallow copy”, which makes the two variables point to the same memory reference. Therefore if we change one, the other changes as well

What directive would you use to hide elements from the HTML DOM by removing them from that DOM not changing their styling?

The ng-If Directive, when applied to an element, will remove that element from the DOM if it’s condition is false.

Explain how $scope.$apply() works in angular js?

$scope.$apply re-evaluates all the declared ng-models and applies the change to any that have been altered (i.e. assigned to a new value)

Explanation: $scope.$apply() is one of the core angular functions that should never be used explicitly, it forces the angular engine to run on all the watched variables and all external variables and apply the changes on their values