Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular evaluate expression as if it were in the HTML

I am looking for a function that will do something like this in Angular:

var testValues = {
    name: 'John Doe',
    number: 15
}
somefunction('Hello, {{name}}, you are {{number}} years old', testValues)
// returns 'Hello, John Doe, you are 15 years old'

I know $eval does something similar to this, but it cannot have double braces inside of it.

like image 578
dyang Avatar asked Jul 14 '16 17:07

dyang


People also ask

How do you write expressions in angular HTML?

AngularJS expressions can be written inside double braces: {{ expression }} . AngularJS expressions can also be written inside a directive: ng-bind="expression" . AngularJS will resolve the expression, and return the result exactly where the expression is written.

What does :: mean in angular?

It means it's used to achieve one time binding. Example. angular.

How are JavaScript expressions called in HTML via AngularJS?

The AngularJS expressions are expressed as {{ }} that associates data to HTML. It displays the data written inside the braces. The expressions are the JavaScript code snippets located inside the bindings.

Can we use data Ng instead of Ng If we want to make your page HTML valid?

You can use data-ng-, instead of ng-, if you want to make your page HTML valid. You will learn a lot more about directives later in this tutorial.


2 Answers

You are probably looking for the $interpolate service.

Example from the documentation:

var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name | uppercase}}!');
expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');

$interpolate compiles a string just like in the templates, and returns a function that outputs a string using the provided context.

like image 170
plamut Avatar answered Oct 18 '22 14:10

plamut


You can manually compile a template. Inject the $compile service and compile the template against a $scope object:

$scope.model = {
  name: 'tom'
};

$compile('<div>Hello {{model.name}}</div>')($scope);

This will return a jqLite object that is wrapped around a DOM object.

like image 3
AJ Meyghani Avatar answered Oct 18 '22 14:10

AJ Meyghani