How to use a filter in a controller?

Inject $filter to your controller function myCtrl($scope, $filter) { } Then wherever you want to use that filter, just use it like this: $filter(‘filtername’); If you want to pass arguments to that filter, do it using separate parentheses: function myCtrl($scope, $filter) { $filter(‘filtername’)(arg1,arg2); } Where arg1 is the array you want to filter on and … Read more

How to add custom validation to an AngularJS form?

Edit: added information about ngMessages (>= 1.3.X) below. Standard form validation messages (1.0.X and above) Since this is one of the top results if you Google “Angular Form Validation”, currently, I want to add another answer to this for anyone coming in from there. There’s a method in FormController.$setValidity but that doesn’t look like a … Read more

AngularJs: How to check for changes in file input fields?

I made a small directive to listen for file input changes. View JSFiddle view.html: <input type=”file” custom-on-change=”uploadFile”> controller.js: app.controller(‘myCtrl’, function($scope){ $scope.uploadFile = function(event){ var files = event.target.files; }; }); directive.js: app.directive(‘customOnChange’, function() { return { restrict: ‘A’, link: function (scope, element, attrs) { var onChangeHandler = scope.$eval(attrs.customOnChange); element.on(‘change’, onChangeHandler); element.on(‘$destroy’, function() { element.off(); }); } … Read more

AngularJS : How to watch service variables?

You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch. In the service: factory(‘aService’, function() { var observerCallbacks = []; //register an observer this.registerObserverCallback = function(callback){ observerCallbacks.push(callback); }; //call this when you know ‘foo’ has been changed var notifyObservers = function(){ angular.forEach(observerCallbacks, function(callback){ callback(); }); … Read more

Confused about Service vs Factory

All angular services are singletons: Docs (see Services as singletons): https://docs.angularjs.org/guide/services Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector. Basically the difference between the service and factory is as follows: app.service(‘myService’, function() { // service is … Read more

AngularJS access parent scope from child controller

If your HTML is like below you could do something like this: <div ng-controller=”ParentCtrl”> <div ng-controller=”ChildCtrl”> </div> </div> Then you can access the parent scope as follows function ParentCtrl($scope) { $scope.cities = [“NY”, “Amsterdam”, “Barcelona”]; } function ChildCtrl($scope) { $scope.parentcities = $scope.$parent.cities; } If you want to access a parent controller from your view you … Read more