【发布时间】: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 是:
<input type="file" ng-file-chosen="" ng-model="model.file" class="ng-pristine ng-valid ng-isolate-scope ng-touched">
什么可能导致指令无法成功运行?
【问题讨论】:
标签: javascript html angularjs angularjs-directive