它AngularJS指令替换文本纳克点击 [英] AngularJS directive to replace text with ng-click in it
问题描述
我试图创造一个角指令,将一组属性操纵一些文本,并将其输出的元素。
我遇到的问题是,我想有一些包裹在一个文本的NG-点击它来调用范围的功能,这将最终打开一个对话框。
我创建了一个非常简单的例子,这里曾经工作会让我上展开: http://jsfiddle.net /伯夫/
app.directive('parseString',函数(){
返回{
限制:'A',
适用范围:{道具:'= parseString},
链接:功能编译(范围,元素,ATTRS){
变种nameHTML ='&下; A HREF =#纳克点击=helloPerson('+ scope.props.name +)>'
+ scope.props.name +'< / A>';
VAR HTML = scope.props.text.replace(世界,nameHTML);
element.html(HTML);
}
}
});
看看我的小提琴的叉:的 http://jsfiddle.net/joakimbeng/aVjtv/1/
为了使它工作,你需要使用$编译提供商。我的例子是不是干净的,但我希望你明白了吧:)
添加$编译依赖和编译您更改HTML:
app.directive('的parseURL',函数($编译){
...
链接:功能编译(范围,元素,ATTRS,控制器){
angular.forEach(value.match(URLPATTERN),功能(URL){
值= value.replace(URL,<目标= \\+ scope.props.target +\\NG点击='的onClick()'>中+ URL +< / A>中) ;
});
//需要的内容在一个div的缠绕,因为
//角度想在根级别只有一个元素
VAR内容= angular.element('< DIV>< / DIV>')。HTML(值).contents();
VAR编译= $编译(内容);
element.html(''); //清除旧文本
element.append(内容); //使用append,而不是一个字符串,因为内容是DOMElements现在,
scope.onClick =功能(){
的console.log(点击);
};
编译(范围); //编译链接元素范围
...
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.
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.
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);
}
}
});
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 :)
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
...
这篇关于它AngularJS指令替换文本纳克点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!