简体   繁体   中英

AngularJS - rendering nested scope vars

Given the following code (simplified for the question):

var app = angular.module("app", []).controller("MainCtrl", function ($scope) {
$scope.data = {
    query: "",
    rnd: Math.random(),
    en: "this is your query: {{data.query}} and ({{rnd}}) is the random number",
    es: "esta es tu consulta: {{data.query}} Y ({{rnd}}) es el número aleatorio"
}
});

and the following view:

<div ng-app="app">
<div ng-controller="MainCtrl">
    <input ng-model="data.query">
    <div>Desired results EN : this is your query: {{data.query}} and ({{data.rnd}}) is the random number</div>
    <div>Desired results ES : esta es tu consulta: {{data.query}} Y ({{data.rnd}}) es el número aleatorio</div>
    <hr>
    <div>{{data.en}}</div>
    <div>{{data.es}}</div>
</div>

Q : What is the right way to render a nested value?

Update : just to clarify, I'm trying to create a language dictionary to my app, some of the captions contains scope vars, and I would like to keep the dictionary structures like this:

{key : sentenceWithVars}

DEMO

Just create two different bindings:

JS

var app = angular.module("app", []).controller("MainCtrl", function ($scope) {
    $scope.data = {
        query: "",
        en: "this is your query: ",
        es: "esta es tu consulta: "
    }
});

HTML

<div ng-app="app">
<div ng-controller="MainCtrl">
    <input ng-model="data.query">
    <div>Current Query:{{data.query}}</div>
    <div>{{data.en}}{{data.query}}</div>
    <div>{{data.es}}{{data.query}}</div>
</div>

Or watch query and update en and es accordingly:

JS

var app = angular.module("app", []).controller("MainCtrl", function ($scope) {
    $scope.data = {
        query: "",
        en: "this is your query: ",
        es: "esta es tu consulta: "
    }
    $scope.$watch("data.query", function (value) {
        $scope.data.en = "this is your query: " + value;
        $scope.data.es = "esta es tu consulta: " + value;
    });
});

HTML

<div ng-app="app">
<div ng-controller="MainCtrl">
    <input ng-model="data.query">
    <div>Current Query:{{data.query}}</div>
    <div>{{data.en}}</div>
    <div>{{data.es}}</div>
</div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM