我試圖創建一個textarea,其中可以寫入其內容,但也可以通過url或上傳的純文本文件填充。所有這一切只需要AngularJS。
我能夠將文件內容加載到鏈接到textarea的同一變量中,但是,在獲取帶有「get」變量的URL內容時,會自動將textarea的內容更改爲給定文本,但上傳時不更新一份文件。
所以,對於初學者來說,我的HTML:Angularjs:更新從文件讀取到textarea的內容
<div id="prot2dna" ng-app="serverExe" ng-controller="p2dCTRL as p2d">
<form novalidate>
<!-- TEXTAREA -->
<textarea class="form-control" ng-model="p2d.query.fasta"></textarea>
<!-- URL SEARCH -->
<div class="input-group">
<input type="text" class="form-control" ng-model="p2d.query.uniac">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="p2d.searchUNIP(p2d.query)">
Search
</button>
</span>
</div>
<!-- READ FILE -->
<span class="btn btn-default my-btn btn-block btn-file">
UPLOAD FILE
<input type="file" on-read-file="p2d.query.fasta">
<!-- Notice here is the same variable that the one linked to textarea -->
</span>
</form>
<div class="checkoutside">
<!-- Here I can see that the variable content is updated, regardless of the fact that it is displayed or not inside the textarea -->
content:<br>{{p2d.query.fasta}}
</div>
</div>
和JavaScript代碼:
var exeApp = angular.module('serverExe', [])
/* THIS DIRECTIVE IS USED TO LOAD THE CONTENT FROM A FILE
IT ACTUALLY UPDATES THE VARIABLE this.query.fasta AND I CAN SEE THAT IN THE .checkoutside
DIVISION, BUT NOTHING HAPPENS INSIDE THE textarea */
.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log(attrs)
var model = $parse(attrs.onReadFile);
console.log(model)
var modelSetter = model.assign;
element.bind('change', function(e) {
scope.$apply(function(){
var reader = new FileReader();
reader.onload = function(){
modelSetter(scope, reader.result);
}
reader.readAsText(element[0].files[0])
});
});
}
};
})
.controller('p2dCTRL', function($http, $scope){
// QUERY
this.query = { 'fasta' : '', 'uniac' : '', 'fastafile': false, 'unierr': true };
//GET CONTENT THROUGH URL
this.searchUNIP = function(query) {
url = 'http://www.uniprot.org/uniprot/'+this.query.uniac+'.fasta';
$http.get(url)
.success(function(data){
// Assign content to variable -> this actually updates the content of the textarea
query.fasta = data;
}).error(function(data){
query.unierr = true;
});
};
});
現在,我完全失去了對如何做到這一點...
謝謝你這麼多。
我不知道,但你試過了變化this.query爲$ scope.query? – Scott 2014-12-04 19:53:22
是的,儘管如此,由於大多數「讀取文件」的例子都是這樣工作的,所以嘗試了......沒有任何改變。但也許我做錯了什麼... – jaumebonet 2014-12-05 12:52:00