Skip to content

Instantly share code, notes, and snippets.

View chandermani's full-sized avatar

Chandermani chandermani

  • London
View GitHub Profile
$scope.foo = $http({method: 'GET', url: '/someUrl'});
<!--In HTML this works-->
<div>{{foo}}</div>
$http({method: 'GET', url: '/someUrl'})
.success(function(data) {
$scope.foo = data;
});
<!--In HTML-->
<p>{{foo}}</p>
//The incorrect way
var employees=$resource('url').query(); //this is async call. Return value of the call is a empty array []
console.log(employees.length); //This is immediately executed so length is 0. Data gets filled in future.
//Right way
$resource('url').query().then(function(data) {
employees = data;
});
element.bind('blur', function () { //some third party component directive
scope.$apply(function(){
$scope.model='someData'; //scope updates have to be done inside the $apply callback
});
});
var element = document.getElementsById('id');
var scope = angular.element(element).scope();
angular.module('module1',[]); //declares a module. Note the second parameter which takes dependencies
angular.module('module1'); //gets a module with name module1, no second parameter
app.factory(‘Items’,function($http) {
var items = [];
return {
list: function() {
var defer=$q.defer();
if (items.length == 0) { // items array is empty so populate it and return list from server to controller
$http.get(‘/?items’).then(function(response) {
items = response.data.items;
defer.resolve(items);
});
@chandermani
chandermani / validationdirectives.js
Last active August 29, 2015 13:57
AngularJS validation directives
angular.module('validation',[])
.directive('customValidator', [function () {
return {
restrict: 'A',
require: 'ngModel',
scope: { validateFunction: '&' },
link: function (scope, elm, attr, ngModelCtrl) {
ngModelCtrl.$parsers.push(function (value) {
var result = scope.validateFunction({ 'value': value });
if (result || result === false) {
<input type="email" ng-model="user.email" name="uEmail" required /><br/>
<div ng-show="form.uEmail.$dirty && form.uEmail.$invalid">
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
<div data-validation-messages='' model-controller='form.email'
required-error="Email id is required."
email-error="Email is not in correct format." />
</div>