AngularJS从指令链接函数传递值到控制器
问题描述:
新手为角。非常简单的问题。我有以下代码。AngularJS从指令链接函数传递值到控制器
我只想显示下面的文件数量。我将fileCount变量绑定到作用域,但它不起作用。
var app = angular.module('fileUploader', []);
app.controller('upload', function($scope){
\t $scope.fileCount = 0;
})
.directive("customDirective", function(){
\t return{
\t \t link: function(scope, el, attrs){
\t \t \t el.bind("change", function(event){
\t \t \t \t console.log(event.target.files.length);
\t \t \t \t scope.fileCount = event.target.files.length;
\t \t \t });
\t \t }
\t }
});
\t <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
\t </head>
\t <body>
\t <div ng-app="fileUploader" ng-controller="upload">
\t \t <input custom-Directive type="file"/>
\t \t <p>The file count is: {{fileCount}}</p>
\t </div> \t \t
\t </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
});
}
}
});
这会揭开序幕,消化周期,你就会看到更新发生,因为EXPEC特德。
感谢您的回答! – catlovespurple
@catlovespurple,没有问题!很高兴它的工作。 –