AngularJS将值从指令链接函数传递到控制器

cat*_*ple 4 javascript angularjs

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

		}
	}

});
Run Code Online (Sandbox Code Playgroud)
	<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>
Run Code Online (Sandbox Code Playgroud)

Jos*_*eam 5

该指令的确从其父项继承了scope属性,但是当您更改对父项属性的引用时,它并不知道会启动摘要周期,因此您必须手动进行操作(请查看此工作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
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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