gpt4 book ai didi

javascript - AngularJs 操作指令中服务响应的数据

转载 作者:行者123 更新时间:2023-11-27 23:03:24 24 4
gpt4 key购买 nike

我的服务收到了一些响应。响应的形式为

 "My data <my-tag>Click me</my-tag>".

响应包含标签“my-tag”。我想编写一个指令,每当呈现响应时,该指令都会操纵标签内的“Click me”内容。自定义标记中的内容应转换为超链接。我怎样才能做到这一点?这是我的示例代码。

我有 myService.js

Service.js

(function() {
function myService() {
this.getData = function(question,questionType) {
anotherService.getList(function(data, status) {
//Here data.text = "<my-tag>Click me</my-tag>"
document.getElementById("additionalData").innerHTML + data.text;
});
}
}
app.addService(app.config.modules.MY_MODULE, "myService", myService);
}());

Directive.js

(function() {
app.directive('myTag', function () {
debugger;
return {
link: function ($scope, element, attrs) {
debugger;
//Convert the text "Click me" into hyperlink
}
};
});
}());

myHtml.html

<html ng-app = "myApp">
<head>
<script>
app.inject(app.config.modules.MY_MODULE, "myService", function(instance) {
myService = instance;
console.log("myService dependency injected successfully.");
});
</script>
</head>
<body ng-controller="myCtrl">
<div>
<img id="getList" onclick="myService.getData()">
</div>
</body>
</html>

最佳答案

您需要编译收到的文本响应,才能使 myTag 正常工作,否则 myTaglink 功能将无法使用根本没有被调用。

总体思路应该是避免直接操作 DOM 并将此任务留给指令。因此,渲染随后出现的一些数据的最佳方法是修改模型(范围)并对应用于应包含要渲染数据的元素的指令中的这些更改使用react。

以下是可能的解决方案之一:

HTML

<!DOCTYPE html>
<html ng-app="app">

<head>
<script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<h1>Hello Plunker!</h1>
<my-list></my-list>
</body>

</html>

JavaScript

angular.module('app', [])
.directive('myTag', function() {
return {
transclude: true,
template: '<a href="#" ng-transclude></a>'
}
})
.directive('myList', ['$compile', function($compile) {
return {
template: '<ul></ul>',
link: function(scope, element) {
scope.$watchCollection('data', function(data) {
if(data && data.length) {
element.empty();
data.forEach(function(item) {
element.append(
$compile( // <= in order to make myTag directive work, you need to compile text
angular.element('<p>'+item+'</p>').contents() // convert text to list of DOM elements wrapped by jqLite/jQuery
)(scope)
);
});
}
}
);
}
}
}])
.run(['$http', '$rootScope', function($http, $rootScope) {
$rootScope.data = [];
$http.get('data.txt').then(function(xhr) {
$rootScope.data.push(xhr.data);
});
}]);

笨蛋

https://plnkr.co/edit/VOl8P7r2DpnayMjRWbvI?p=preview

关于javascript - AngularJs 操作指令中服务响应的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36841322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com