I am building a Rails app but using AngularJS for bits of the front end.
Is it possible to store {{expressions}}
as a $scope.variable
value?
Code:
Here is the angular controller
// I am pulling data from the rails controller via the gon gem. $scope.entertainmentTemplate = gon.active_entertainment_template.description;
Which translates to:
$scope.description = "{{productName}} is a great product and also has awesome {{additionalInfo}}. These are some more example words, blah blah..";
Defined variables in angular controller: $scope.productName = "Test product"; $scope.additionalInfo = "test additional information";
$scope.productName = "Test product"; $scope.additionalInfo = "test additional information";
My question is how do I render the above $scope.description
to the view so that it displays like so:
"Test product is a great product and also has awesome test additional information. These are some more example words, blah blah.."
Please let me know if any additional context is needed.
Here is an image of the application to show context:
You can use a function to mimic a "computed" property like so:
$scope.fullDescription = function () {
return productName + " is a great product and also has awesome " +
additionalInfo + ". These are some more example words, blah blah..";
};
And you can bind to it just like a variable in your markup:
<div ng-bind="fullDescription()"></div>
you can use angular $parse
using regular expression you can search for the variable and then parse it.
The example below it is not a 100% accurate but you will get the idea
Like:
$scope.description = "{{productName}} is a great product and also has
awesome {{additionalInfo}}. These are some more example words, blah
blah..".replace(/{{(.*?)}}/g,
function(item,a){ var getter = $parse(a); return getter($scope); });
Now, I am just answering an option on how. However, I do not believe this is the optimal solution to the problem.
I figured it out. The solution was $interpolate
Example:
//Assign the gon variable from the rails controller
$scope.entertainmentTemplate = gon.active_entertainment_template.description;
// Interpolate the variable with the controller $scope as the scope and
assign it to the model you wish.
$scope.description = $interpolate($scope.entertainmentTemplate)($scope);
Make sure you add the $interpolate
service to the controller like so:
var app = angular.module('myApp', []);
app.controller('listingFormCtrl',['$scope', '$interpolate', function($scope, $interpolate) {
}]);
This will replace all unrendered instance of {{expression variables}} in the assigned controller scope.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.