用 ng-click 替换文本的 AngularJS 指令 [英] AngularJS directive to replace text with ng-click in it
问题描述
我正在尝试在 Angular 中创建一个指令,该指令采用一组属性来操作某些文本并将其输出到元素.
I am trying to create a directive in Angular that takes a set of properties manipulates the some text and outputs it to the element.
我遇到的问题是我想将一些文本包裹在 ng-click 中,这是从范围调用一个函数,最终会打开一个对话框.
The problem i'm having is I want to have some of the text wrapped in a ng-click which is to call a function from the scope that will in the end open a dialog box.
我在这里创建了一个非常简单的例子,一旦工作将让我扩展它:http://jsfiddle.net/BEuvE/
I have created a very simple example here which once working will let me expand on it: http://jsfiddle.net/BEuvE/
app.directive('parseString', function() {
return {
restrict: 'A',
scope: { props: '=parseString' },
link: function compile(scope, element, attrs) {
var nameHTML = '<a href="#" ng-click="helloPerson('+scope.props.name+')">'
+scope.props.name+'</a>';
var html = scope.props.text.replace('world', nameHTML);
element.html(html);
}
}
});
推荐答案
看看我的叉子:http://jsfiddle.net/joakimbeng/aVjtv/1/要使其工作,您需要使用 $compile 提供程序.我的例子不是那么干净,但我希望你明白这一点:)
Take a look at my fork of your fiddle: http://jsfiddle.net/joakimbeng/aVjtv/1/ To make it work you need to use the $compile provider. My example isn't that clean, but I hope you get the point :)
添加 $compile 依赖项并编译更改后的 html:
Add the $compile dependency and compile your changed html:
app.directive('parseUrl', function($compile) {
...
link: function compile(scope, element, attrs, controller) {
angular.forEach(value.match(urlPattern), function(url) {
value = value.replace(url, "<a target=\"" + scope.props.target + "\" ng-click='onClick()'>" + url +"</a>");
});
// The wrapping of the content in a div is required because
// Angular wants only one element at root level
var content = angular.element('<div></div>').html(value).contents();
var compiled = $compile(content);
element.html(''); // Clearing old text
element.append(content); // Using append because "content" is DOMElements now, instead of a string
scope.onClick= function () {
console.log('clicked');
};
compiled(scope); // Linking compiled elements to scope
...
这篇关于用 ng-click 替换文本的 AngularJS 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!