gpt4 book ai didi

javascript - Angularjs:更新从文件读取的内容到textarea

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:34 24 4
gpt4 key购买 nike

我正在尝试创建一个文本区域,可以在其中写入其内容,但也可以通过 url 或上传的纯文本文件来填充。所有这一切只需要 AngularJS。
我能够将文件内容加载到链接到 textarea 的同一变量中,但是,在将带有“get”的 URL 内容获取到变量中时,自动将 textarea 的内容更改为给定的文本,上传文件时它不会更新.
所以,对于初学者来说,我的 HTML:

<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;
});
};
});

现在,我完全不知道该怎么做......

非常感谢。

最佳答案

啊。一种方法是像这样使用 $parse:

var onFileReadFn = $parse(attrs.onReadFile);
var reader = new FileReader();

reader.onload = function() {

var fileContents = reader.result;

// invoke parsed function on scope
scope.$apply(function() {
onFileReadFn(scope, {
'contents' : fileContents
});
});
};

reader.readAsText(element[0].files[0]);

完整示例在这里:http://jsfiddle.net/200eoamf/1

关于javascript - Angularjs:更新从文件读取的内容到textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com