[英]AngularJS directive to replace text with ng-click in it
我試圖在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);
}
}
});
看看我的小提琴叉子: 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
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.