簡體   English   中英

AngularJS-是否可以將{{expressions}}存儲為$ scope.variable值?

[英]AngularJS - Is it possible to store {{expressions}} as a $scope.variable value?

我正在構建一個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.productName = "Test product"; $scope.additionalInfo = "test additional information";

我的問題是如何將上面的$scope.description呈現給視圖,使其顯示如下:

“測試產品是一個很棒的產品,並且還提供了很棒的測試附加信息。這些都是更多示例性的單詞,等等。”

請讓我知道是否需要任何其他上下文。


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

現在,我只是在回答一個選項。 但是,我認為這不是解決問題的最佳方法。

我想到了。 解決方案是$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}}實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM