【问题标题】:AngularJS custom directive not updating model with chosen fileAngularJS 自定义指令不使用所选文件更新模型
【发布时间】:2015-06-07 10:12:31
【问题描述】:

我已经编写了我的第一个自定义指令 ng-file-chosen,它应该将在 <input> 元素中选择的文件名分配给通过 ng-model 传入的绑定。

在下面的 sn-p 中,ng-file-chosen 结果绑定到model.file,下面有一个绑定来显示选择的值。

var app = angular.module('app', []);
app.controller('controller', function ($scope) {
    $scope.model = {
        file: "No file selected"
    };
});

var directive = function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attributes) {
            element.change(function (e) {
                var files = (e.srcElement || e.target).files;
                scope.ngModel = files[0];
            });
        }
    };
};

app.directive('ngFileChosen', directive);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="controller">
    <input type="file" ng-file-chosen="" ng-model="model.file"/>
    <p>{{model.file}}</p>
</div>

不幸的是,选择文件时,什么也不会发生,并且绑定不会更新。我已经尝试检查生成的 HTML,它看起来好像链接函数根本没有运行,因为输入元素在运行时的完整 HTML 是:

&lt;input type="file" ng-file-chosen="" ng-model="model.file" class="ng-pristine ng-valid ng-isolate-scope ng-touched"&gt;

什么可能导致指令无法成功运行?

【问题讨论】:

标签: javascript html angularjs angularjs-directive


【解决方案1】:

您的代码存在一些问题。

  1. 您不需要对 ngModel 进行隔离绑定,因为您的指令中已经需要 ngModel。您甚至根本不需要使用隔离范围。一般来说,当你创建一个属性指令时,你不应该使用独立的作用域。

  2. 您需要 scope.$apply 以传播您对范围的更改。

    scope.$apply(function() {
        scope.model.file = files[0].name;  
    });
    

我还做了一些其他的小修复。 Here 是您的代码的更新工作插件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多