添加后加载时,ng-click不会触发

Snæ*_*ørn 9 translation angularjs angularjs-ng-click

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

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

标记:

<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>
Run Code Online (Sandbox Code Playgroud)

角度的东西:

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);
      });
    }
  };
}]);
Run Code Online (Sandbox Code Playgroud)

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

Kay*_*ave 10

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

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

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

使用这个你将替换:

<p ng-bind-html="alink"></p>
Run Code Online (Sandbox Code Playgroud)

<p compile="alink"></p>
Run Code Online (Sandbox Code Playgroud)

并添加此指令:

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);
      }
    );
  };
Run Code Online (Sandbox Code Playgroud)

});


rai*_*amp 10

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

<p translate="varWithDirective" translate-compile></p>
Run Code Online (Sandbox Code Playgroud)

会编译而不需要编写自定义指令.

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