2013-05-06 130 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 
    ...