In this artricle we will try to create angularjs directive which will display only first 10 characters of element text and link that opens the whole text when user clicked on it.
Before clicking:
After clicking:
To simplify the example i'm using the code of
angular phonecat tuttorial.
In the example we need to display the
snippet property of phone object
html markup:
Directive declaration:
/* app\js\directives.js */
var phonecatDirectives = angular.module('phonecatDirectives', []);
phonecatDirectives.directive('zippy', function () {
return {
restrict: "E",
replace: true,
transclude: false,
scope: { title:'@zippyTitle' },
template: '
{{title}}
' ,
// The linking function will add behavior to the template
link: function(scope, element, attrs) {
var opened=true;
scope.$watch('title',function(newVal, oldVal){
element.html(scope.title.substr(0,10)+' ...');
// Title element
var title = angular.element(element.children()[0]),
// Opened / closed state
opened = true;
// Clicking on title should open/close the zippy
title.on('click', toggle);
})
// Toggle the closed/opened state
function toggle() {
if(opened) element.text(scope.title)
opened = !opened;
//element.removeClass(opened ? 'closed' : 'opened');
//element.addClass(opened ? 'opened' : 'closed');
}
}
};
});