gpt4 book ai didi

javascript - AngularJS 将指令链接函数的值传递给 Controller

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

Angular 新手。非常直截了当的问题。我有以下代码。

我只想在下面显示文件数。我将 fileCount 变量绑定(bind)到范围,但它不起作用。

var app = angular.module('fileUploader', []);

app.controller('upload', function($scope){
$scope.fileCount = 0;
})

.directive("customDirective", function(){
return{
link: function(scope, el, attrs){
el.bind("change", function(event){
console.log(event.target.files.length);
scope.fileCount = event.target.files.length;
});

}
}

});
	<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-app="fileUploader" ng-controller="upload">
<input custom-Directive type="file"/>
<p>The file count is: {{fileCount}}</p>
</div>
</body>

最佳答案

该指令确实从其父级继承范围属性,但它不知道在您更改对父级属性的引用时启动摘要循环,因此您必须手动执行此操作(看看这个 working jsbin ):

.directive("customDirective", function(){
return{
link: function(scope, el, attrs){
el.bind("change", function(event){
scope.fileCount = event.target.files.length;

scope.$apply(); // notice this
});
}
}
});

这将启动摘要周期,您将看到更新按预期进行。

关于javascript - AngularJS 将指令链接函数的值传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408493/

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