9

我正在尝试进行变量替换,同时还可以使用ngClick使其可点击。

我做了一个plunker demo(点击按钮,观察输入框保持不变)

标记:

<body ng-controller="Ctrl">
  <input type="text" id="input" name="input" ng-model="myValue" test>
  <p translate="VARIABLE_REPLACEMENT" translate-values="{{ 'translationData' }}"></p>
  <p ng-bind-html="alink"></p>
</body>

角的东西:

var translations = {
  VARIABLE_REPLACEMENT: 'Hi, {{name}}'
};

var app = angular.module('myApp', ['pascalprecht.translate', 'ngSanitize']);

app.config(['$translateProvider', function ($translateProvider) {
  // add translation table
  $translateProvider.translations(translations);
}]);

app.controller('Ctrl', ['$scope', '$sce', function ($scope, $sce) {
  $scope.translationData = { name: 'foo'};

  $scope.setValue = function(value) {
    $scope.myValue = value;
  };
}]);

app.directive('test', ['$translate', '$sce', function ($translate, $sce) {
  return {
    require: 'ngModel',
    scope: false,
    link: function (scope, element, attrs, ctrl) {
      scope.$watch(attrs.ngModel, function (value) {
        var a = $translate('VARIABLE_REPLACEMENT', {
          name: '<button type="button" ng-click="setValue(\'foobar\')">click me</button>'
        });
        scope.alink = $sce.trustAsHtml(a);
      });
    }
  };
}]);

ng-click="setValue('foobar')"问题是:为什么单击按钮时不触发。它应该在输入字段中设置值“foobar”。

4

3 回答 3

10

Angular 没有标记$compile$sce所以 Angular 没有处理你ng-click的指令并将指令附加到它上面。

为了在你的字符串中使用 Angular 指令并让它们生效,你需要将字符串发送到 Angular 的$compile函数。

一种简单的方法是使用以下指令(在此处找到:https ://github.com/angular/angular.js/issues/4992 )

使用它,您将替换:

<p ng-bind-html="alink"></p>

<p compile="alink"></p>

并添加此指令:

angularApp.directive('compile', function($compile) {
  // directive factory creates a link function
  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);
      }
    );
  };

});

于 2013-12-03T20:10:48.613 回答
10

与此同时,这个问题有一个官方的解决方案:

<p translate="varWithDirective" translate-compile></p>

无需编写自定义指令即可进行编译。

欲了解更多信息: https ://github.com/angular-translate/angular-translate/issues/184

于 2014-05-04T19:57:52.143 回答
1

您在 angular 之外创建了一个元素。我不确定 pascalprescht 是如何工作的,但你需要告诉元素 $compile ( docs )

于 2013-12-03T20:07:34.717 回答