在angularjs中

时间:2017-06-08 10:48:50

标签: angularjs

如何在插值内插值?

我正在使用我编写消息字符串并使用{{ vm.variable }}的文件,但我无法在HTML上显示带有变量值的字符串。

输入字符串(在JS中):"Welcome {{name}} to the World."

所需的输出字符串(用HTML格式):"Welcome John Smith to the world."

查看下面的代码

(function() {

    'use strict';

    angular
        .module('app', [])
        .value('_MSG_', {
                "signup": "Welcome {{name}} to the World.",
                "login": "last login from {{location}}"
        }).controller('MessageController', function($scope, $parse, $interpolate, _MSG_){
            var vm = this;
            vm.name = "John Smith";
            vm.location = "India";
            vm.welcomeMessage = _MSG_.signup;
            //========trial 1 =======
            // vm.finalString = $interpolate(vm.welcomeMessage); 
            // nothing happens but
            //=====trial 2=====
            // set {{vm.name}} in _MSG_.signup and do below
            // vm.finalString = $parse(_MSG_).assign($scope, vm.name);
            // ERROR [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 9 of the expression [Weclome {{vm.name}}.] starting at [{{vm.name}}.].
        });
})();
<html ng-app="app">
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MessageController as vm ">
    {{ vm.welcomeMessage }} ==> Welcome John Smith to the world


    // trial 1

    {{ vm.finalString }}
</body>
</html>

1 个答案:

答案 0 :(得分:4)

您需要将$interpolate绑定到this\vm

赞:$interpolate(vm.welcomeMessage)(this);

样本:

&#13;
&#13;
angular
  .module('app', [])
  .value('MSG', {
    "signup": "Welcome {{name}} to the World.",
    "login": "last login from {{location}}"
  }).controller('MessageController', function($scope, $parse, $interpolate, MSG) {
    var vm = this;
    vm.name = "John Smith";
    vm.location = "India";
    vm.welcomeMessage = MSG.signup;
    vm.finalString = $interpolate(vm.welcomeMessage)(this);
  });
&#13;
<html ng-app="app">
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MessageController as vm ">
    {{ vm.welcomeMessage }} ==> Welcome John Smith
    
    <br>// trial 1<br>
    {{ vm.finalString }}
</body>
</html>
&#13;
&#13;
&#13;