Created
January 24, 2014 13:51
-
-
Save leeroybrun/8597615 to your computer and use it in GitHub Desktop.
AngularJS tips & tricks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ------------------------------------------------------ | |
// Set focus on an element | |
// Source : http://stackoverflow.com/a/14837021/1160800 | |
// ------------------------------------------------------ | |
app.directive('focusMe', function($timeout, $parse) { | |
return { | |
//scope: true, // optionally create a child scope | |
link: function(scope, element, attrs) { | |
var model = $parse(attrs.focusMe); | |
scope.$watch(model, function(value) { | |
if(value === true) { | |
$timeout(function() { | |
element[0].focus(); | |
}); | |
} | |
}); | |
// to address @blesh's comment, set attribute value to 'false' | |
// on blur event: | |
element.bind('blur', function() { | |
scope.$apply(model.assign(scope, false)); | |
}); | |
} | |
}; | |
}); | |
// ------------------------------------------------------ | |
// Delayed function call/search | |
// ------------------------------------------------------ | |
angular.module('app.directives'). | |
directive('delayedSearch', ['$timeout', function($timeout) { | |
return { | |
restrict: 'E', | |
scope: { | |
'queryModel': '=', | |
'queryCallback': '&' | |
}, | |
link: function (scope, element, attrs) { | |
var timer = false; | |
scope.$watch('queryModel', function() { | |
if (timer) { | |
$timeout.cancel(timer); | |
} | |
timer = $timeout(function () { | |
scope.queryCallback(); | |
}, 1000); | |
}); | |
} | |
}; | |
}]); | |
// ------------------------------------------------------ | |
// nl2br filter | |
// ------------------------------------------------------ | |
angular.module('app.filters') | |
.filter('nl2br', function(){ | |
return function(text) { | |
return text.replace(/\n/g, '<br/>'); | |
}; | |
}); | |
// ------------------------------------------------------ | |
// HTML to trusted - ng-bind-html-unsafe alternative | |
// Source : http://stackoverflow.com/a/21254635/1160800 | |
// ------------------------------------------------------ | |
angular.module('myApp') | |
.filter('to_trusted', ['$sce', function($sce){ | |
return function(text) { | |
return $sce.trustAsHtml(text); | |
}; | |
}]); | |
//<div ng-bind-html="html.to.embed | to_trusted"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment