[英]AngularJS Pass value from directive link function to controller
新手到Angular。 非常直截了當的問題。 我有以下代碼。
我只想在下面顯示文件計數。 我將fileCount變量綁定到范圍,但它不起作用。
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>
該指令確實從其父級繼承了作用域屬性,但是當您更改對父屬性的引用時,它不知道是否啟動摘要循環,因此您必須手動執行此操作(請查看此工作的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
});
}
}
});
這將啟動摘要周期,您將看到更新按預期發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.