范围变量未在指令之外设置

Scope Variable Not Being Set Outside of Directive

本文关键字:外设 设置 指令 变量 范围      更新时间:2023-09-26

>我正在尝试创建一个 AngularJS 指令,该指令将文件名从 <input type="file"> 元素发送到文件上传工厂。 这项工作基于以下博客文章:

http://odetocode.com/blogs/scott/archive/2013/07/05/a-file-input-directive-for-angularjs.aspx

我定义了我的 HTML 元素:

<div file-input="file" on-change="readFile()"></div>

设置相关指令后:

myApp.directive('fileInput', function ($parse)
{
    return {
        restrict: "A",
        template: "<input type='file' />",
        replace: true,
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileInput);
            var onChange = $parse(attrs.onChange);
            element.bind('change', function () {
                model.assign(scope, element[0].files[0]);
                console.log(element[0].files[0]);  // correctly references selected file
                scope.$apply();
                console.log(model(scope));  // correctly references selected file
                onChange(scope);
            });
        }
    };
});

当我从元素中选择一个文件时,将触发change事件,并且我的两个console.log调用都会打印出对所选文件的引用。 但是尝试在控制器中打印出$scope.file并不反映文件选择:

$scope.file = "nothing";
$scope.readFile = function()
{
    $scope.progress = 0;
    console.log($scope.file);  // print "nothing"
    fileReaderFactory.readAsDataUrl($scope.file, $scope)
        .then(function (result) {
            $scope.imageSrc = result;
        });
};

我缺少什么不允许控制器正确设置和保留从指令发送的值?

更新

我进行了以下更新,但我的范围变量仍未更新。 调用了我的更改函数,但它没有注意到赋予myModel的任何新值。

.HTML:

<file-input my-model="fileRef" my-change="readFile()"></file-input>

指令(input标签更新为text以进行测试):

myApp.directive('fileInput', function ($parse)
{
    return {
        restrict: "AE",
        template: "<input type='text' />",
        replace: true,
        scope: {
            myModel: "=",
            myChange: "&"
        },
        link: function (scope, element, attrs) {
            element.bind('change', function () {
                scope.myChange();
            });
        }
    };
});

控制器:

$scope.fileRef = "nothing";
$scope.readFile = function()
{
    $scope.progress = 0;
    console.log($scope.fileRef);  // prints "nothing"
    fileReaderFactory.readAsDataUrl($scope.fileRef, $scope)
        .then(function (result) {
            $scope.imageSrc = result;
        });
};

在指令对象中添加scope: {file-input: '='},以便在指令的作用域和父作用域之间具有双向绑定。

尝试将文件添加到链接函数。 我遇到了同样的问题,这就是为我解决它的原因。

据我所知,链接充当模板的控制器(范围)。

但是,让我感到困惑的一件事是,当我从控制器中的$scope方法中添加要$scope的属性时,模板会看到新属性。 当添加到$scope方法之外(仍在控制器中)时,它不是。