【问题标题】:AngularJS - Is it possible to store {{expressions}} as a $scope.variable value?AngularJS - 是否可以将 {{expressions}} 存储为 $scope.variable 值?
【发布时间】:2017-09-12 23:45:06
【问题描述】:

我正在构建一个 Rails 应用程序,但在前端使用 AngularJS。

是否可以将{{expressions}} 存储为$scope.variable 值?

代码:

这是角度控制器

// I am pulling data from the rails controller via the gon gem. $scope.entertainmentTemplate = gon.active_entertainment_template.description;

翻译为:

$scope.description = "{{productName}} is a great product and also has awesome {{additionalInfo}}. These are some more example words, blah blah..";

角度控制器中定义的变量: $scope.productName = "Test product"; $scope.additionalInfo = "test additional information";

我的问题是如何将上面的$scope.description 渲染到视图中,使其显示如下:

“测试产品是一个很棒的产品,并且还有很棒的测试附加信息。这些是更多的示例词,等等等等。”

如果需要任何额外的上下文,请告诉我。


更新 1:

这是显示上下文的应用程序图像:

【问题讨论】:

    标签: javascript jquery ruby-on-rails angularjs ruby


    【解决方案1】:

    您可以使用函数来模仿“计算”属性,如下所示:

        $scope.fullDescription = function () {
           return productName + " is a great product and also has awesome " +
                  additionalInfo + ". These are some more example words, blah blah..";
        };
    

    你可以像在你的标记中绑定一个变量一样绑定它:

    <div ng-bind="fullDescription()"></div>
    

    【讨论】:

    • 如何知道变量变化时调用函数?
    • 这个答案对 Angular 如何决定重新运行该函数有一个很好、彻底的解释:stackoverflow.com/questions/30437563/…
    • 谢谢,我明白了
    • @SteveDanner 感谢您的回复。我确实考虑过这种方法并将其用于应用程序的其他部分。唯一的问题是,有许多描述,并且变量将位于每个位置的不同位置。所以我需要一种方法来呈现我在原始问题中所说的表达式。我曾考虑过$compile,但不太确定该怎么做。
    【解决方案2】:

    你可以使用角度$parse 使用正则表达式你可以搜索变量然后解析它。

    下面的例子不是 100% 准确,但你会明白的

    喜欢:

    $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); });
    

    现在,我只是回答一个选项。但是,我不认为这是解决问题的最佳方案。

    【讨论】:

      【解决方案3】:

      我想通了。解决方案是$interpolate

      例子:

      //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);
      

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

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

      这将替换分配的控制器范围内所有未渲染的 {{expression variables}} 实例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多