如何将async数据从指令传递给控制器​​?

vzh*_*hen 3 angularjs angularjs-directive angularjs-controller uploadcare

我想将第三方api(uploadcare)编译成指令.

api将在async上传后返回数据信息,然后我想对我的控制器中的返回数据做一些事情,但我不得不知道如何将返回数据从指令传递给控制器​​.以下是我的代码.

在js

        link: function (scope, element, attrs) {
            //var fileEl  = document.getElementById('testing');
            var a = function() {

                var file    = uploadcare.fileFrom('event', {target: fileEl});
                file.done(function(fileInfo) {

                    //scope.$apply(attrs.directUpload)
                   //HERE IS MY PROBLEM.
                   //How can I get the fileInfo then pass and run it at attrs.directUpload

                }).fail(function(error, fileInfo) {

                }).progress(function(uploadInfo) {
                  //Show progress bar then update to node
                  console.log(uploadInfo);
                });
            };

            element.bind('change', function() {a()});
        }
Run Code Online (Sandbox Code Playgroud)

在HTML中

<input type="file" direct-upload="doSomething()">
Run Code Online (Sandbox Code Playgroud)

在控制器中

$scope.doSomething = function() {alert(fileInfo)};
Run Code Online (Sandbox Code Playgroud)

Kla*_*r_1 8

$parent在您的情况下,AngularJS允许在具有指定值的上下文中执行表达式doSomething().

这是你需要做的:

  1. 在指令定义中,标记directUpload为表达式:
scope: {
    directUpload: "&"
}
Run Code Online (Sandbox Code Playgroud)
  1. done回调中,请致电:
scope.directUpload({fileInfo: fileInfo})
Run Code Online (Sandbox Code Playgroud)
  1. 更新标记:
<input type="file" direct-upload="doSomething(fileInfo)">
Run Code Online (Sandbox Code Playgroud)

总结:scope.directUpload现在是一个回调,它使用specifeid值在属性内执行表达式.这样你可以将任何东西传递给控制器doSomething.

阅读$ compile docs以获取详细说明和示例.

您可能会发现有用的示例:

angular
.module("app", [])
.directive("onDone", function ($timeout) {
  function link (scope, el, attr) {
    $timeout(function () {
      scope.onDone({
        value: "something"
      });
    }, 3000)
  }
  return {
    link: link,
    scope: {
      onDone: "&"
    }
  }
})
.controller("ctrl", function ($scope) {
  $scope.doneValue = "nothing";
  $scope.done = function (value) {
    $scope.doneValue = value;
  };
})
Run Code Online (Sandbox Code Playgroud)
<body ng-controller="ctrl">
  Waiting 3000ms
  <br>
<div on-done="done(value)">
  Done: {{doneValue}}
</div>
</body>
Run Code Online (Sandbox Code Playgroud)