I need to implement an angular directive that triggers before all events like ng-click whenever the view value changes. This directive should be called as the first action when the view is changed.
Check out the JSFiddle example.
angular.module('myApp', []);
angular
.module('myApp').directive('format', ['$filter', function ($filter) {
return {
require: 'ngModel',
scope: {
val : '=val'
},
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
if(attrs.symbol == '$')
return $filter(attrs.format)(ctrl.$modelValue, '$')
else
return $filter(attrs.format)(ctrl.$modelValue)
});
elem.bind('change', function(event) {
var a = elem.val();
var plainNumber = a.split('.').filter(function(e){
return (e.length > 0);
}).join('.');
var i = 0;
if(isNaN(parseFloat(plainNumber))){
i = (attrs.symbol == '$') ? 1 : 3;
}
var num = plainNumber.substring(i, plainNumber.length).replace(/,/g,'');
if(attrs.symbol == '$')
elem.val($filter('currency')(num, attrs.symbol));
else
elem.val($filter('currency')(num));
var n =parseFloat(num);
scope.val = Number(n);
if(!scope.$$phase) {
scope.$apply();
}
});
}
};
}]);
Is there a way to ensure the directive gets called every time?