Angular JS - textarea的动态加载模型,不渲染大括号变量

时间:2017-09-12 21:24:41

标签: javascript jquery ruby-on-rails angularjs

我正在构建一个rails应用程序,并在前端使用一些AngularJS。

目标:编辑动态加载的描述模板,根据填写的其他输入更改模板的区域。

例如,$scope.description为:"This {{productName}} is really great. It also has {{subtitle}}, and some more words."

但是,当我将模板加载到描述模型时,它不会在描述模型中呈现大括号括起来的变量。

正如您在上面看到它的方式一样,而不是用相应的$scope变量值替换大括号变量。

例如,我希望说明如下所示:"This test product is really great. It also has test subtitle and some more words."

查看此示例图片: Example image

这里有一些代码:

// From AngularJS Controller

$scope.productName = "test product";
$scope.subtitle = "test subtitle";

$scope.description = $(".entertainmentTemplate").data("template");

//In the view template description is stored as data because it is set dynamically
- @active_templates.each do |template|
            %li
                %a{ remote: true, data: {template: "#{template.description}"}}= template.name

// View of the input fields 
= f.text_field :subtitle, "ng-model" => "productName"
= f.text_field :subtitle, "ng-model" => "subtitle"

// Description view
= f.text_area :description, "ng-model" => "description"

如果我需要包含更多背景信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

我明白了。解决方案是服务$interpolate

$interpolate将替换指定控制器范围内的所有未呈现的{{expression variables}}实例。

这是更新后的代码:

// From AngularJS Controller

$scope.productName = "test product";
$scope.subtitle = "test subtitle";

// I used the gon gem to store the value from the rails controller then 
passed it to the JS like so:

$scope.entertainmentTemplate = gon.active_entertainment_template.descripti

// Interpolate the variable with the controller $scope as the scope and 
assign it to the model you wish.

$scope.description = $interpolate($scope.entertainmentTemplate)($scope);

// View of the input fields 
= f.text_field :subtitle, "ng-model" => "productName"
= f.text_field :subtitle, "ng-model" => "subtitle"

// Description view
= f.text_area :description, "ng-model" => "description"

确保将$interpolate服务添加到控制器,如下所示:

var app = angular.module('myApp', []);
app.controller('listingFormCtrl',['$scope', '$interpolate', function($scope, $interpolate) {

}]);