我正在尝试进行变量替换,同时使用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'.
角没有$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); } ); };
});
与此同时,该问题有一个官方解决方案:
<p translate="varWithDirective" translate-compile></p>
会编译而不需要编写自定义指令.
欲了解更多信息:https: //github.com/angular-translate/angular-translate/issues/184