如何通过Angular中的$resource发送来自自定义指令的输入值

How to send input value from custom directive through $resource in Angular?

本文关键字:自定义 指令 输入 Angular 何通过 中的 resource      更新时间:2023-09-26

我已经找到了在自定义指令中使用ngModel的答案,我理解这个概念,但我不确定我是否理解如何在使用$resource时实现它。

我成功地将"文件"作用域注入到指令中,并进行了api调用,但返回到服务器的值为null。我确信Angular指令的实现是我的错所在。

指令.js

angular.module('pro').directive('buyLinkBox', function() {
     return {
        restrict: "AE",
        replace: true,
        template: '<md-input-container md-no-float md-block><label style="font-size:2.2vh">Buy Link for {{file.filename}}</label><input type="text" ng-blur="sendLink()" ng-model="file.buyLink" name="buyLink" id="buyLink"/></md-input-container>',
        scope: {
            file: '=',
        },
        controller: function($scope, $route ,BuyLinkService){
            $scope.sending = BuyLinkService.get({
                FileId: $scope.file._id
            });
            $scope.sendLink = function() {
                $scope.sending.$sendLink(function() {
                    $route.reload();
                }, function(errorResponse) {
                    alert('nope');
                });
            };

        }
     }
});

html

 <buy-link-box file="file"></buy-link-box>

经过一番推导,我找到了一个解决方案。

我将ngModel添加到指令范围中,并将其包含在我的html中。但主要的问题是,我的资源在得到我的数据之前就被调用了。修复当然很简单。在启动PUT api调用之前,我创建了一个回调并将所需字段设置为输入变量。

希望这能帮助到别人。

指令.js

    angular.module('pro').directive('buyLinkBox',['BuyLinkService', '$route', 
        function(BuyLinkService, $route) {
         return {
            restrict: "E",
            replace: true,
            template: '<md-input-container md-no-float md-block><label style="font-size:2.2vh">Buy Link for {{file.filename}}</label><input type="text" ng-blur="sendLink()" ng-model="ngModel" name="buyLink" id="buyLink"/></md-input-container>',
            scope: {
                file: '=',
                ngModel: '='
            },
            link: function(scope, element, attrs){
                scope.sendLink = function() {
                    BuyLinkService.get({MixedId: scope.file._id}, function(data){
                    data.buyLink = scope.file.buyLink;
                    data.$sendLink(function(file) {
                        alert(file.buyLink);
                        $route.reload();
                    }, function(errorResponse) {
                        alert('nope');
                    });
                })
              }
            }
         }
  }]);

html

<buy-link-box ng-model="file.buyLink" file="file"></buy-link-box>