AngularJS指令用ng-click替换文本

时间:2013-05-06 11:22:30

标签: javascript angularjs angularjs-directive

我正在尝试在Angular中创建一个指令,它采用一组属性来操纵一些文本并将其输出到元素。

我遇到的问题是我希望将一些文本包含在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);
    }
  } 
});

1 个答案:

答案 0 :(得分:3)

看看我的小提琴:http://jsfiddle.net/joakimbeng/aVjtv/1/ 要使它工作,您需要使用$ compile提供程序。我的例子不是那么干净,但我希望你明白这一点:)

添加$ 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
     ...