对于代码,我从中获取灵感:
https://codepen.io/alexandergaziev/pen/JdVQQm
因此,对于HTML,我已经这样做了:
<div class="file_input_div">
<div class="file_input">
<label class="image_input_button mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-js-ripple-effect mdl-button--colored">
<i class="material-icons">file_upload</i>
<input id="file_input_file" class="none" type="file"
ng-model="file1"
onchange="angular.element(this).scope().changeInputText(this);
angular.element(this).scope().changeState();"/>
</label>
</div>
<div id="file_input_text_div" class="mdl-textfield mdl-js-textfield textfield-demo"
ng-model="filetextdiv">
<input class="file_input_text mdl-textfield__input"
type="text" disabled readonly id="file_input_text"
ng-model="filetext" />
<label class="mdl-textfield__label" for="file_input_text">
</label>
</div>
</div>
在相应的控制器中:
$scope.changeInputText = function(){
console.log($scope.file1);
console.log($scope.filetext);
console.log($scope.filetextdiv);
var str = $scope.file1.value;
var i;
if (str.lastIndexOf('\\'))
{
i = str.lastIndexOf('\\') + 1;
}
else if (str.lastIndexOf('/'))
{
i = str.lastIndexOf('/') + 1;
}
$scope.filetext.value = str.slice(i, str.length);
};
$scope.changeState = function() {
console.log("Coucou");
if ($scope.filetext.value.length != 0)
{
if (!$scope.filetextdiv.classList.contains("is-focused"))
{
$scope.filetextdiv.classList.add('is-focused');
}
}
else
{
if ($scope.filetextdiv.classList.contains("is-focused"))
{
$scope.filetextdiv.classList.remove('is-focused');
}
}
}
但是有一个问题,我不明白为什么:
当我选择文件时,会调用控制器中的函数。
但是,值(由ng-model,file1,filetext和filetextdiv设计)未定义。
为什么?
答案 0 :(得分:1)
ng-model
input type=file
的指令
app.directive('fileModel', function () {
return {
restrict: 'A',
require: "ngModel",
link: function(scope, elem, attrs, ngModel) {
elem.on('change', function(e){
ngModel.$setViewValue(elem[0].files);
});
}
};
});
<input type="file" ng-model="vm.files" file-model />
在对文件执行POST操作时,务必将Content-Type header设置为undefined
。
var config = { headers: {
"Content-Type": undefined,
}
};
$http.post(url, vm.files[0], config)
.then(function(response) {
vm.result = "SUCCESS";
}).catch(function(response) {
vm.result = "ERROR "+response.status;
});
默认情况下,AngularJS框架使用内容类型application/json
。通过设置Content-Type: undefined
,AngularJS框架省略了允许XHR API设置内容类型的内容类型标头。
有关详细信息,请参阅MDN Web API Reference - XHR Send method
但是,值(由ng-model,file1,filetext和filetextdiv设计)未定义。
为什么file1
未定义?核心ng-model
指令不适用于type=file
注意:并非所有提供的功能都适用于所有输入类型。具体而言,
ng-model
不支持通过input[file]
进行数据绑定和事件处理。
为什么filetext
未定义?输入已禁用。
<input class="file_input_text mdl-textfield__input"
type="text" disabled readonly id="file_input_text"
ng-model="filetext" />
为什么filetextdiv
未定义? ng-model
指令不适用于<div>
元素。
<div id="file_input_text_div" class="mdl-textfield mdl-js-textfield textfield-demo"
ng-model="filetextdiv">
这会回答你的问题吗?