Angular js input type = file不会控制数据

时间:2017-04-26 06:39:56

标签: javascript jquery angularjs

你好我是角度js的新手,我想尝试在我的html中获取我的public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch(position) { case 0: Tab1 tab1 = new Tab1(); return tab1; case 1: Tab2 tab2 = new Tab2(); return tab2; case 2: Tab3 tab3 = new Tab3(); return tab3; } return null; // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). //return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "APPROVAL"; case 1: return "NONE"; case 2: return "NONE"; } return null; } } 的数据..但是当我控制它时它只是说未定义

HTML

input type = "file"

JS

   <input type="file" ng-model="data.img" ng-click="upload()"/>

4 个答案:

答案 0 :(得分:1)

ng-model不支持文件类型输入。需要使用类似

的指令手动将值设置为ngModel
.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
})

像这样调用指令

<input type="file" files-input ng-model="data.img" ng-click="upload()"/>

现在检查控制台

答案 1 :(得分:1)

您可以使用指令执行此操作。请参见示例here

答案 2 :(得分:1)

  • 但最简单的方法是使用HTML5 API而不是directive,而FileReader HTML非常简单:

    添加

在您的控制器中定义&#39;添加&#39;方法:

$scope.add = function(){
  var f = document.getElementById('file').files[0],
      r = new FileReader();
  r.onloadend = function(e){
    var data = e.target.result;
    //send your binary data via $http or $resource or do anything else with it
  }
  r.readAsBinaryString(f);
}

参考here

答案 3 :(得分:0)

使用<input type="file" id="file1" name="file1" multiple onchange="angular.element(this).scope().fileNameChanged('file1')"/>代替您的代码,

JS

 $scope.fileNameChanged = function(inputField) {


var file = document.getElementById(inputField).files;
console.log(file);