Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string that contains data bindings in AngularJS

I have a backend rendered template that returns a JSON object that contains a string that needs some dynamic data bindings for example...

sampleLogic = {
  "1": "Sample static text and some {{ dynamic_text }}." 
}

By default the string is escaped, what's the best way in angular to convert dynamic_text to bind to $scope.dynamic_text?

JS:

 var sampleLogic = {
    "1": "Sample static text and some {{ dynamic_text }}."
};

function parseMe($scope) {
    $scope.copy = sampleLogic['1'];
    $scope.dynamic_text = "dynamic text woooot";
}

HTML:

<div ng-app>
    <div ng-controller="parseMe">
        <div ng-bind-html-unsafe="copy"></div>
    </div>
</div>

Fiddle: http://jsfiddle.net/RzPM3/

like image 234
Rob B Avatar asked Aug 19 '13 15:08

Rob B


People also ask

What is data binding in AngularJS?

Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

Can you explain how data binding works in AngularJS?

Data-binding in AngularJS apps is the automatic synchronization of data between the model and view components. The way that AngularJS implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times.

What kind of data binding does AngularJS support?

AngularJs support one-way binding as well as two-way binding. Most templating systems work with one-way databinding. They merge the model component and template together into a view. When the merge occurrs, the model data is bound to the view.

What is AngularJS one-way data binding?

One-way data binding in AngularJS means binding data from Model to View (Data flows from the scope/controller to the view). 'ng-bind' is an angular directive used for achieving one-way data binding.


1 Answers

You can use $interpolate module and easily achieve it like this

var dynamic_text = {
    'dynamic_text': "dynamic text woooot"
};
$scope.copy = $interpolate(sampleLogic['1'])(dynamic_text);

DEMO

like image 170
zs2020 Avatar answered Oct 20 '22 01:10

zs2020