2013-05-04 62 views

回答

2

原文:

app.directive('fileSelect', function() { 
    var template = '<input type="file" name="files"/>'; 
    return function(scope, elem, attrs) { 
    var selector = $(template); 
    elem.append(selector); 
    selector.bind('change', function(event) { 
     scope.$apply(function() { 
     scope[ attrs.fileSelect ] = event.originalEvent.target.files; 
     }); 
    }); 
    scope.$watch(attrs.fileSelect, function(file) { 
     selector.val(file); 
    }); 
    }; 
}); 

刪除了需要全jQuery和利用某些Angular directive features的(模板和雙向範圍變量綁定):

app.directive('fileSelect', function() { 
    return { 
    template:'<input type="file" name="files"/>', 
    scope:{fileSelect:'='}, 
    link:function(scope,el,attrs){ 
     el.bind('change', function(event) { 
     scope.$apply(function() { 
     scope.fileSelect = event.target.files; 
     }); 
    }); 
    } 
    } 
}); 

新plnkr:​​

+0

+1不錯的緊湊解決方案。 – Neil 2013-05-04 18:20:32

+0

+1令人印象深刻,那太快了..謝謝一噸 – bsr 2013-05-04 18:21:06