When to set caret position in $parser method of angularJS - angularjs

I'm using ngModelController for formatting using input element. But I'm unable to set the caret position, if the user tries to enter any digit in the beginning or in the middle. As the caret alway jumps at the end.
What is the best place for calling set cursor?
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue}`);
console.log(`cursorPos = ${cursor.getCursorPos(elem[0])}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
// $log.info(`newVal = ${newVal}`);
elem.val(newVal);
return plainNumber;
});

similar question:
Preserving cursor position with angularjs
But I've added the below code, may be useful to other.
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue} | viewValue = ${viewValue} | cursorPos = ${cursor.getCursorPos(elem[0])} | oldVal = ${oldVal}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
if(newVal === viewValue) {
return viewValue;
}
// $log.info(`newVal = ${newVal}`);
var lastCursorPos = cursor.getCursorPos(elem[0]);
elem.val(newVal);
ngModelController.$setViewValue(newVal);
ngModelController.$render();
//cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
elem[0].setSelectionRange(lastCursorPos + 1, lastCursorPos + 1);
oldVal = newVal;
return plainNumber;
});

Related

Trying to create a service to build my NgTable

I'm trying to create a service that return me the NgTableParams so I don't need to do it every time I need a table.
I was able to do it and it worked, but only if i have only one table using it in my controller, if I try to use it in a second table look's like the service mess the parameters of the fist and second table and stop working.
I tried to change the service to a factory and tried to make a angular.copy of the service so each copy create one different table yet noting worked.
Every time i need a table it is like this:
$scope.tableParams = NgTableDataService.getGenericTableParams($scope.onboardcomputerstatus, $scope.filterObject);
$scope.searchTable = { filter: '' };
$scope.tableParams = new NgTableParams({
count: $scope.session.user.tablePagination,
filter: $scope.searchTable.filter
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
var funcFilter = function (item) {
var pfilter = params.filter().filter.toUpperCase();
return item.onboardComputer.id.toString().indexOf(pfilter) >= 0
|| (!!item.onboardComputer.remainingMonitoringMsgs ? item.onboardComputer.remainingMonitoringMsgs : "").toString().indexOf(pfilter) >= 0
|| $filter('date')((!!item.onboardComputer.oldestMonitoringTimestamp ? item.onboardComputer.oldestMonitoringTimestamp : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastCommunicatio ? item.lastCommunicatio : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastRegister ? item.lastRegister : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| item.vehicle.code.toUpperCase().indexOf(pfilter) >= 0
|| item.vehicle.name.toUpperCase().indexOf(pfilter) >= 0;
}
filteredData = params.filter() ? $filter('filter')($scope.onboardcomputerstatus, funcFilter) : $scope.onboardcomputerstatus;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL) {
params.count(filteredDataLength);
}
if (params.total() <= params.count()) {
params.page(1);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
So I tried to do a factory like this:
angular.module('control-room').factory('NgTableDataFactory', function (
$filter, MY_CONSTANTS, NgTableParams, Session
) {
var ngTableObj = {};
ngTableObj.tableData = {};
ngTableObj.filterObject = {};
ngTableObj.session = Session.get();
ngTableObj.defaultDateFormat = (!!ngTableObj.session.company ? ngTableObj.session.company.dateHourFormatHTML : null);
ngTableObj.tablePagination = (!!ngTableObj.session.user ? ngTableObj.session.user.tablePagination : MY_CONSTANTS.QTD_REG_TAB_INDEX);
ngTableObj.NgTableParamsFactory = new NgTableParams({
count: ngTableObj.tablePagination,
filter: ""
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
if (!!params.filter().filter && params.filter().filter != '') {
var pfilter = params.filter().filter.toUpperCase();
} else {
var pfilter = '';
}
let filteredData = params.filter() ? $filter('filter')(ngTableObj.tableData, ngTableObj.funcFilterFactory(ngTableObj.filterObject, pfilter)) : ngTableObj.tableData;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL && filteredDataLength > 0) {
params.count(filteredDataLength);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
ngTableObj.findPropertyValue = function (obj, propertyList){
let aux = obj;
for(property of propertyList){
aux = aux[property];
}
return aux
};
ngTableObj.funcFilterFactory = function (f_Object, p_filter) {
return function (item) {
var result = false;
if (!!f_Object.columnNames) {
f_Object.columnNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = (propertyValue ? propertyValue.toString() : "").toUpperCase().indexOf(p_filter) >= 0 || result;
}
});
};
if (!!f_Object.translateNames) {
f_Object.translateNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = $filter('translate')((propertyValue != null ? propertyValue.toString() : "").toUpperCase()).indexOf(p_filter) >= 0 || result;
}
});
}
if (!!f_Object.dateFormat) {
f_Object.dateFormat.forEach(function (row) {
if (typeof(row) == 'string') {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = propertyValue ? $filter('date')(propertyValue, ngTableObj.defaultDateFormat).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}else {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row[0].split('.'));
result = propertyValue ? $filter('date')(propertyValue, row[1]).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}
});
}
return result;
};
};
return ngTableObj
});
and in the controller is like this:
$scope.filterObject = {
columnNames : ['onboardComputer.id', 'onboardComputer.remainingMonitoringMsgs', 'vehicle.code', 'vehicle.name' ],
dateFormat : ['onboardComputer.oldestMonitoringTimestamp', 'lastCommunicatio', 'lastRegister' ]
};
$scope.tableFactory = NgTableDataFactory;
$scope.tableFactory.tableData = $scope.onboardcomputerstatus;
$scope.tableFactory.filterObject = $scope.filterObject;
$scope.tableFactory.session = Session.get();
$scope.tableParams = $scope.tableFactory.NgTableParamsFactory
Like I said, this way it work well, but only if i use one time, if I have 2 tables it stop working

how to add text in textarea cursor position by angularjs

I want sample code to add a text to textarea angularjs code, can any one help.
Writing an SMS with some custom name field like {userName} #userName# etc. These are onclick events, when user clicks, respected text should be added in cursor position in textarea box.
Check this link and use the directive in your app
http://plnkr.co/edit/Xx1SHwQI2t6ji31COneO?p=preview
app.directive('myText', ['$rootScope', function($rootScope) {
return {
link: function(scope, element, attrs) {
$rootScope.$on('add', function(e, val) {
var domElement = element[0];
if (document.selection) {
domElement.focus();
var sel = document.selection.createRange();
sel.text = val;
domElement.focus();
} else if (domElement.selectionStart || domElement.selectionStart === 0) {
var startPos = domElement.selectionStart;
var endPos = domElement.selectionEnd;
var scrollTop = domElement.scrollTop;
domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length);
domElement.focus();
domElement.selectionStart = startPos + val.length;
domElement.selectionEnd = startPos + val.length;
domElement.scrollTop = scrollTop;
} else {
domElement.value += val;
domElement.focus();
}
});
}
}
}])

How to add thousand separating commas for numbers in angularJS?

I simply want to convert a string of numbers to a number which will be displayed using thousand separated commas.
var value = "123456";
I want to display "123,465" in a grid.
I have looked some documentation on this but everything is about displaying it in HTML.
I want to display this in a dynamic grid.
function numberRenderer (params) {
return new Number (params.value);
}
I want to format the number so that I can convert that into a string for display.
Use a filter ...
HTML usage
{{ number_expression | number : fractionSize}}
Js usage
$filter('number')(number, fractionSize)
I appreciated the answer from #jbrown, but I was also hoping to find some type of solution to add commas to an input field as the user enters numbers. I ended up finding this directive which proved to be exactly what I needed.
HTML
<input type="text" ng-model="someNumber" number-input />
JAVASCRIPT
myApp.directive('numberInput', function($filter) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(modelValue) {
return setDisplayNumber(modelValue, true);
});
// it's best to change the displayed text using elem.val() rather than
// ngModelCtrl.$setViewValue because the latter will re-trigger the parser
// and not necessarily in the correct order with the changed value last.
// see http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/
// for an explanation of how ngModelCtrl works.
ngModelCtrl.$parsers.push(function(viewValue) {
setDisplayNumber(viewValue);
return setModelNumber(viewValue);
});
// occasionally the parser chain doesn't run (when the user repeatedly
// types the same non-numeric character)
// for these cases, clean up again half a second later using "keyup"
// (the parser runs much sooner than keyup, so it's better UX to also do it within parser
// to give the feeling that the comma is added as they type)
elem.bind('keyup focus', function() {
setDisplayNumber(elem.val());
});
function setDisplayNumber(val, formatter) {
var valStr, displayValue;
if (typeof val === 'undefined') {
return 0;
}
valStr = val.toString();
displayValue = valStr.replace(/,/g, '').replace(/[A-Za-z]/g, '');
displayValue = parseFloat(displayValue);
displayValue = (!isNaN(displayValue)) ? displayValue.toString() : '';
// handle leading character -/0
if (valStr.length === 1 && valStr[0] === '-') {
displayValue = valStr[0];
} else if (valStr.length === 1 && valStr[0] === '0') {
displayValue = '';
} else {
displayValue = $filter('number')(displayValue);
}
// handle decimal
if (!attrs.integer) {
if (displayValue.indexOf('.') === -1) {
if (valStr.slice(-1) === '.') {
displayValue += '.';
} else if (valStr.slice(-2) === '.0') {
displayValue += '.0';
} else if (valStr.slice(-3) === '.00') {
displayValue += '.00';
}
} // handle last character 0 after decimal and another number
else {
if (valStr.slice(-1) === '0') {
displayValue += '0';
}
}
}
if (attrs.positive && displayValue[0] === '-') {
displayValue = displayValue.substring(1);
}
if (typeof formatter !== 'undefined') {
return (displayValue === '') ? 0 : displayValue;
} else {
elem.val((displayValue === '0') ? '' : displayValue);
}
}
function setModelNumber(val) {
var modelNum = val.toString().replace(/,/g, '').replace(/[A-Za-z]/g, '');
modelNum = parseFloat(modelNum);
modelNum = (!isNaN(modelNum)) ? modelNum : 0;
if (modelNum.toString().indexOf('.') !== -1) {
modelNum = Math.round((modelNum + 0.00001) * 100) / 100;
}
if (attrs.positive) {
modelNum = Math.abs(modelNum);
}
return modelNum;
}
}
};
});
AngularJS Directive was found from: AngularJS number input formatted view
https://jsfiddle.net/benlk/4dto9738/
Very appreciative of what Anguna posted. The only thing it was missing for me was handling the decimal places like currency. I wanted it to automatically add 2 decimal places to the displayed value. However, this should only occur on initial display and then again when leaving a field. I updated the code to handle that scenario.
var app = angular.module("myApp", []);
app.directive('currencyInput', function ($filter) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function (modelValue) {
var displayValue = setDisplayNumber(modelValue, true);
displayValue = setDecimal(displayValue);
return displayValue;
});
// it's best to change the displayed text using elem.val() rather than
// ngModelCtrl.$setViewValue because the latter will re-trigger the parser
// and not necessarily in the correct order with the changed value last.
// see http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/
// for an explanation of how ngModelCtrl works.
ngModelCtrl.$parsers.push(function (viewValue) {
setDisplayNumber(viewValue);
return setModelNumber(viewValue);
});
// occasionally the parser chain doesn't run (when the user repeatedly
// types the same non-numeric character)
// for these cases, clean up again half a second later using "keyup"
// (the parser runs much sooner than keyup, so it's better UX to also do it within parser
// to give the feeling that the comma is added as they type)
elem.bind('keyup focus', function () {
setDisplayNumber(elem.val());
});
elem.bind('blur', function () {
// Add Decimal places if they do not exist
var valStr = elem.val().toString();
valStr = setDecimal(valStr);
elem.val(valStr);
});
function setDisplayNumber(val, formatter) {
var valStr, displayValue;
if (typeof val === 'undefined') {
return 0;
}
valStr = val.toString();
displayValue = valStr.replace(/,/g, '').replace(/[A-Za-z]/g, '');
displayValue = parseFloat(displayValue);
displayValue = (!isNaN(displayValue)) ? displayValue.toString() : '';
// handle leading character -/0
if (valStr.length === 1 && valStr[0] === '-') {
displayValue = valStr[0];
} else if (valStr.length === 1 && valStr[0] === '0') {
displayValue = '';
} else {
displayValue = $filter('number')(displayValue);
}
// handle decimal
if (!attrs.integer) {
if (displayValue.indexOf('.') === -1) {
if (valStr.slice(-1) === '.') {
displayValue += '.';
} else if (valStr.slice(-2) === '.0') {
displayValue += '.0';
} else if (valStr.slice(-3) === '.00') {
displayValue += '.00';
}
} // handle last character 0 after decimal and another number
else {
if (valStr.slice(-1) === '0') {
displayValue += '0';
}
}
}
if (attrs.positive && displayValue[0] === '-') {
displayValue = displayValue.substring(1);
}
if (typeof formatter !== 'undefined') {
return (displayValue === '') ? 0 : displayValue;
} else {
elem.val((displayValue === '0') ? '' : displayValue);
}
}
function setModelNumber(val) {
var modelNum = val.toString().replace(/,/g, '').replace(/[A-Za-z]/g, '');
modelNum = parseFloat(modelNum);
modelNum = (!isNaN(modelNum)) ? modelNum : 0;
if (modelNum.toString().indexOf('.') !== -1) {
modelNum = Math.round((modelNum + 0.00001) * 100) / 100;
}
if (attrs.positive) {
modelNum = Math.abs(modelNum);
}
return modelNum;
}
function setDecimal(val) {
// Add Decimal places if they do not exist
var valStr = val.toString();
// If no decimal then add it
if (valStr.indexOf('.') === -1) {
valStr += '.00';
}
else {
var decimalDigits = valStr.length - (valStr.indexOf('.') + 1);
var missingZeros = 2 - decimalDigits;
for (var i = 1; i <= missingZeros; i++) {
valStr += '0';
}
}
return valStr;
}
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp">
<input type="text" ng-model="myModelValue" currency-input />
</div>

angular's equivalent of ko.utils.arrayMap or adding extra properties to returned data array?

Im in the process of converting a knockout app to angular, I currently get an array of objects from the server but I would like to extend each object by adding some extra properties.
In knockout I would do the following:
var mappedResults = ko.utils.arrayMap(results, function(item) {
item.selected = ko.observable(true);
item.viewPreview = ko.observable(false);
return new reed.search.Candidate(item, self.viewModel.fileDownloadFailCookieName);
});
and the Candidate viewmodel:
reed.search.Candidate = function(data, fileDownloadFailCookieName) {
debugger
if (data == null) {
throw 'Error: cannot initiate candidate';
}
this.fileDownloadFailCookieName = fileDownloadFailCookieName;
this.candidateId = data.CandidateId;
this.name = data.Name;
this.surname = data.Surname;
this.forename = data.Forename;
this.displayLocation = data.DisplayLocation;
this.lastJobDetails = data.LastJobDetails;
this.displayPayRate = data.DisplayPayRate;
this.lastSignIn = data.LastSignIn;
this.downloadCVUrl = data.DownloadCVUrl;
this.additionalInfo = data.AdditionalInfo;
this.isAvailable = (data.IsAvailable) ? "Availability confirmed" : "";
this.availableMornings = data.AvailableMornings;
this.availableAfternoons = data.AvailableAfternoons;
this.availableEvenings = data.AvailableEvenings;
this.availableWeekends = data.AvailableWeekends;
this.availableShiftWork = data.AvailableShiftWork;
this.availableNights = data.AvailableNights;
this.availabilityUpdatedOn = data.AvailabilityUpdatedOn;
this.availabilityUpdatedOnDate = "| <strong>Availability updated</strong> " + data.AvailabilityUpdatedOn;
this.isAvailableForSomething =
this.availableMornings
|| this.availableAfternoons
|| this.availableEvenings
|| this.availableWeekends
|| this.availableShiftWork
|| this.availableNights;
this.viewPreview = ko.observable(false);
this.selected = ko.observable(false);
this.hasBeenNotified = ko.observable(false);
this.select = function() {
this.selected(true);
};
this.deSelect = function() {
this.selected(false);
};
this.HasFlagSet = function(availability) {
return availability ? "availabilitySelected" : "availabilityNotSelected";
};
this.ajaxCvDownload = function() {
var path = window.location.href,
iframeError,
cookieName = this.fileDownloadFailCookieName;
// download path
path = path.match(/(.+\/)/ig)[0];
if (path.match(/home/ig)) {
path = path.replace('home', this.downloadCVUrl);
} else {
path = this.downloadCVUrl;
};
$('<iframe />').attr('src', path)
.hide()
.appendTo('body').load(function() {
var message = decodeURIComponent(reed.shared.utils.getCookie(cookieName));
message = message.replace(/\+/g, " ");
if (message.length > 0 && message != "null") {
reed.shared.utils.showMessage(message, "Download Failed");
}
});
}
}
how can I achieve the same functionality in angular?
You don't need angular for this array itself contains a map function and all modern browsers support it.
var mappedResults = results.map(function(item) {
item.selected = true;
item.viewPreview = false;
return new reed.search.Candidate(item,
self.viewModel.fileDownloadFailCookieName);
});
Some other things you can improve. Firstly if you are using webapi to return data, use a formatter that fixes casing.Check this blog http://blogs.msmvps.com/theproblemsolver/2014/03/26/webapi-pascalcase-and-camelcase/
Once you have the formatter lines such as these are not required
this.surname = data.Surname;
You can then use angular.extend to copy properties into your class.

How to check if expression will have a value after evaluating

Let's say I have a following template:
"foo['x'] = '{{ myVar }}';"
Is there an angular way of checking if evaluating this against my current scope will give myVar some value ? I've got an array of such small templates and I only want to include them in the document when values are truthy. I was hoping either $interpolate, $parse or $eval might come in handy here. I know for sure that $interpolate is useless. What about the other two ? Maybe it's at least possible to get the name of the assigned value/expression ?
EDIT
I wasn't specific enough. What I was trying to achieve, was checking in advance if for example template '{{ myVar }}' evaluated against the current scope will return an empty string or value of the scope variable (if it exists). The case was really specific - when traversing an array of short templates I wanted to know if a template will return as an empty string or not, and only include it in my final html if it doesn't.
I'm not sure what are you trying to achieve, but to if you want to check if myVar is truthy in current scope, you can:
{{myVar ? "aw yiss" : "nope"}}
Evaluates to "aw yiss" if myVar is truthy and "nope" otherwise.
I ended up with a modified $interpolate provider but maybe someone knows a shorter solution :
app.provider('customInterpolateProvider', [
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$sce', function($parse, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
allOrNothing = !!allOrNothing;
var startIndex,
endIndex,
index = 0,
expressions = [],
parseFns = [],
textLength = text.length,
exp;
var getValue = function (value) {
return trustedContext ?
$sce.getTrusted(trustedContext, value) :
$sce.valueOf(value);
};
var stringify = function (value) {
if (value == null) {
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
value = angular.toJson(value);
}
return value;
};
var parseStringifyInterceptor = function(value) {
try {
return stringify(getValue(value));
} catch(err) {
console.err(err.toString());
}
};
while(index < textLength) {
if ( ((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1) ) {
exp = text.substring(startIndex + startSymbolLength, endIndex);
expressions.push(exp);
parseFns.push($parse(exp, parseStringifyInterceptor));
index = endIndex + endSymbolLength;
} else {
break;
}
}
if (!expressions.length && !text.contains(startSymbol) && !text.contains(endSymbol)) {
expressions.push(text);
}
if (!mustHaveExpression) {
var compute = function(values) {
for(var i = 0, ii = expressions.length; i < ii; i++) {
if (allOrNothing && angular.isUndefined(values[i])) {
return;
}
expressions[i] = values[i];
}
return expressions.join('');
};
return angular.extend(function interpolationFn(context) {
var i = 0;
var ii = expressions.length;
var values = new Array(ii);
try {
if (ii && !parseFns.length) {
return expressions[0];
} else {
for (; i < ii; i++) {
values[i] = parseFns[i](context);
}
return compute(values);
}
} catch(err) {
console.err(err.toString());
}
}, {
exp: text,
expressions: expressions,
$$watchDelegate: function (scope, listener, objectEquality) {
var lastValue;
return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
var currValue = compute(values);
if (angular.isFunction(listener)) {
listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
}
lastValue = currValue;
}, objectEquality);
}
});
}
}
return $interpolate;
}];
}
]);
Lines below were added because in some cases I have a predefined text in my short template and I always want to render it :
if (!expressions.length && !text.contains(startSymbol) && !text.contains(endSymbol)) {
expressions.push(text);
}
if (ii && !parseFns.length) {
return expressions[0];
} else {

Resources