Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Expression in Expression

Is there a way to have AngularJS evaluate an expression within model data?

HTML:

<p>
{{Txt}}
</p>


Model:

    { 
     Txt: "This is some text {{Rest}}"
    }

    {
      Rest: "and this is the rest of it."
    }

The end result would be: This is some text and this is the rest of it.

like image 430
AnotherDeveloper Avatar asked May 16 '14 23:05

AnotherDeveloper


People also ask

What is :: In AngularJS?

It's used to bind model from your controller to view only. It will not update your controller model if you change this from your view. It means it's used to achieve one time binding. Example. angular.

Which of the following is a valid AngularJS expression?

AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{{ attrBinding }}">{{ textBinding }}</span> , but also used directly in directive attributes such as ng-click="functionExpression()" . For example, these are valid expressions in AngularJS: 1+2.

What is $eval in AngularJS?

$eval evaluates an Angular expression against/on the current scope.

Can we have nested controllers in AngularJS?

A controller can contain properties and functions. Controllers are used for controlling the application data of an AngularJS application. In this article, we will see the nested controllers in AngularJS and will understand their implementation with the help of examples.


2 Answers

You can use the $interpolate service to interpolate the string...

function ctrl ($scope, $interpolate) {
    $scope.Txt = "This is some text {{Rest}}";
    $scope.Rest = "and this is the rest of it.";
    $scope.interpolate = function (value) {
        return $interpolate(value)($scope);
    };
}

<div ng-app ng-controller="ctrl">
    <input ng-model="Txt" size="60" />
    <p>{{ Txt }}</p>
    <p>{{ interpolate(Txt) }}</p>
</div>

JSFiddle

like image 61
Anthony Chu Avatar answered Sep 20 '22 12:09

Anthony Chu


You can execute JS within the brackets:

<p>{{Txt + ' ' + Rest}}</p>

Or create a function that returns the text you want:

$scope.getText = function() {
  return $scope.Txt + ' ' + $scope.Rest;
}

<p>{{getText()}}</p>
like image 24
SomeKittens Avatar answered Sep 21 '22 12:09

SomeKittens