Reputation: 1544
I want to do something similar to (in my html):
{{ Customer.Name }}
when Customer.Name is
"{{ Customer.FirstName + ' ' + Customer.LastName }}"
How can I achieve this? The Customer.Name-String is a dynamic configuration that I read from the server. I would like to do this on several places in my application so I don't want a static code-behind-function that does this for me.
All I want is that Angular evaluates the expression recursively.
Upvotes: 1
Views: 689
Reputation: 1176
You can use the method $eval
() of $scope
to achieve this.
For example, your Controller would define your customer object like this:
function TestCtrl ($scope) {
$scope.customer = {
firstname : 'Darth',
lastname : 'Vader',
name : 'customer.firstname + " " + customer.lastname'
};
$scope.ev = $scope.$eval;
}
Then in your view you could use the configuration string like this:
<h1 ng-controller="TestCtrl">Hello {{$eval(customer.name)}}!</h1>
It is important that your customer.name
property does not contain the curly brackets!
See this plunkr for a working example: http://plnkr.co/edit/r524cP6OAOBBzDReLNw4?p=preview
Upvotes: 1
Reputation: 1070
There are 2 way to do it.
Create a directive that use a customer object and concatenate both First and Lastname.
angular.module('customer.directives',[]).
.directive('customerName', function() {
restrict : 'EA', // both element and attr will work in case you are using a customer directive
replace : true,
scope : {
Customer : '='
},
template : '{{Customer.FirstName}} {{Customer.Lastname}}'
});
Example Call :
<div ng-repeat="Customer in Customers">
<customer-name='Customer'></customer-name>
</div>
Or you could use a function inside the CustomerService to send your controller the full name already concatenated.
Ex :
angular.module('Customer.Services', [])
.factory('CustomerService', function(){
return {
/* other methods here */
getFullName : function(Customer) {
return Customer.FirstName + ' ' + Customer.LastName
}
}
});
angular.module('Customer.Controllers', [])
.controller('CustomerController', function($scope.CustomerService) {
$scope.service = CustomerService.query();
$scope.getFullName = fucntion(customer) {
return CustomerService.getFullName(customer);
}
}
)
And call it with :
<div ng-repeat="Customer in Customers">
{{getFullName(Customer)}}
</div>
Upvotes: 1