gpt4 book ai didi

javascript - 如果我们使用 $http 获取数据,数据不会从一个自定义指令传输到另一个自定义指令

转载 作者:行者123 更新时间:2023-11-28 18:56:23 26 4
gpt4 key购买 nike

我有两个不同的自定义指令,并且想要将数据从一个指令传递到另一个指令。数据来自服务器调用。问题是 http 作为异步调用不会预先返回数据,并且另一个小部件的 Controller 不会接收它,并且它会在没有数据的情况下渲染它的 html。这是完整的代码(我删除了一些在问题中可能没有意义的代码)-

访问服务器的服务是 -

angular.module('myModule')

.service('MyService', [
'$http',

function($http) {
this.getData = (someId) => {
var url = someUrl + '/' + someId;
return $http.get(url);
};
}
]);

第一个调用服务并在要传输到另一个指令的范围内设置“anotherData”的指令是 -

angular.module('myModule')

.directive('myDirective', ['MyService',
function(MyService) {

return {
restrict: 'E',
scope: {
data: '='
},
templateUrl: 'my-template.html',

controller: ['$scope', function($scope) {

MyService.getData ($scope.data.id).then((response) => {
$scope.anotherData = response.data;
});

}]
}

}]);

我调用另一个指令的 my-template.html 是(注意 anotherData 在这里传递 -

<other-directive mode="display" data="data" anotherData="anotherData" ></other-directive>

应该接收“anotherData”但没有给我结果的另一个指令是 -

angular.module('otherModule')

.directive('otherDirective', [function() {
return {
restrict: 'E',
scope: {
id: '@',
data: '=',
mode: '@',
anotherData: '@'
},
templateUrl: 'other-template.html',

controller: ['$scope', '$element', function ($scope, $element) {

console.log("other data in widget after server call:");
///THIS IS UNDEFINED.
console.log($scope.anotherData);
}],

link: function ($scope, $element) {
}
}
}]);

and other-template.html 有 iframe 来显示 youtube 小部件 -

<iframe width="{{anotherData.videoWidth}}"
height="{{anotherData.videoHeight}}"
src="{{anotherData.videoURL}}" frameborder="0" allowfullscreen></iframe>

最佳答案

您应该使用破折号而不是驼峰式大小写,如下所示:

<other-directive mode="display" data="data" another-data="anotherData" ></other-directive>

此外,您要绑定(bind)文本而不是双向绑定(bind)对象,因此请将指令中的定义更改为:

anotherData: '='

关于javascript - 如果我们使用 $http 获取数据,数据不会从一个自定义指令传输到另一个自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33570173/

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