我有这样的代码:

<div ng-repeat="(key, category) in shop.categories">
  <div ng-repeat="(key, group) in category.groups">
    <span ng-bind="'groupPrice-' + ($parent.$index + 1) + '-' + ($index + 1)"></span>
  </div>
</div>


我想以示例<span>$scope.groupPrice-1-1等的$scope.groupPrice-1-2值显示。

如何解析ng-bind以显示作用域的值?现在,此显示范围的名称,而不是值。

最佳答案

尝试使用angular指令将字符串评估为对象属性。

html代码:

<div ng-app="vkApp">
    <div ng-controller="vkController">
        <span compile="groupPrice_1_1"></span>
        <br>
        <span compile="groupPrice_1_2"></span>
    </div>
</div>


角度脚本:

angular.module('vkApp', []);

angular.module('vkApp')
  .controller('vkController', ['$scope', '$compile', function ($scope, $compile) {
      $scope.groupPrice_1_1 = "Hi man !";
      $scope.groupPrice_1_2 = "lol !";
  }]);

  // declare a new module, and inject the $compileProvider
angular.module('vkApp')
  .directive('compile', ['$compile', function ($compile) {
      return function(scope, element, attrs) {
          scope.$watch(
            function(scope) {
               // watch the 'compile' expression for changes
              return scope.$eval(attrs.compile);
            },
            function(value) {
              // when the 'compile' expression changes
              // assign it into the current DOM
              element.html(value);

              // compile the new DOM and link it to the current
              // scope.
              // NOTE: we only compile .childNodes so that
              // we don't get into infinite loop compiling ourselves
              $compile(element.contents())(scope);
            }
        );
    };
}]);


JSFiddle here

angular ng-bind-html and directive within it

注意:您必须将$scope.groupPrice-1-1改为$scope.groupPrice_1_1

希望本文对您有所帮助。

关于javascript - 如何在插值中解析作用域名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40299711/

10-11 19:29