2013-05-06 126 views
0

我想在Angular中创建一个指令,它需要一组属性来操作一些文本并将其输出到元素。AngularJS指令用ng-click替换文本

我遇到的问题是我想将一些文本包裹在一个ng-click中,它将从最后打开一个对话框的范围调用一个函数。

我已经在这里创造一个非常简单的例子,这一次的工作会让我上展开: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); 
    } 
    } 
}); 

回答

3

看看我的小提琴的叉:http://jsfiddle.net/joakimbeng/aVjtv/1/ 要使它工作,你需要使用$ compile提供者。我的例子是不是干净的,但我希望你明白了吧:)

添加$编译依赖和编译改变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 
    ...