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

标签 javascript angularjs youtube-api

我有两个不同的自定义指令,并且想要将数据从一个指令传递到另一个指令。数据来自服务器调用。问题是 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/

相关文章:

java - Spring Restful Service将所有url重定向到index.html

angularjs - 二进制文件损坏 - 如何使用 AngularJS 下载二进制文件

php - 去除黑边 4 :3 on youtube thumbnails

iframe - 无法嵌入某些YouTube视频,iframe会显示 “the video contains content from WMG. it is restricted from playback on certain sites”

javascript - PJAX 和 CSS 转换

javascript - 如何选择两个h2之间的所有元素

javascript - Tween.js |即使我循环播放,我的补间也不会更新

javascript - 如何使用 JavaScript 查找数组中最早的日期

google-api - 来自 Google 的电子邮件 : Using a Google product name as the project in OAuth consent screen

javascript - createSVGMatrix 不是函数 : SVG loading on Firefox but not on Chrome