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

 红殿_真红王道哥哥 发布于 2023-02-13 10:17

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

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

标记:


  
  

角度的东西:

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: ''
        });
        scope.alink = $sce.trustAsHtml(a);
      });
    }
  };
}]);

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

2 个回答
  • 角没有$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);
          }
        );
      };
    

    });

    2023-02-13 10:18 回答
  • 与此同时,该问题有一个官方解决方案:

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

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

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

    2023-02-13 10:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有