4

Newbie to Angular. Very straightforward question. I have the following code.

I just want to show the file count underneath. I bind the fileCount variable to scope, but it doesn't work.

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>

1 Answer 1

5

The directive does inherit the scope properties from its parent, but it doesn't know to kick off the digest cycle whenever you change a reference to a parent property, so you have to do that manually (check out this 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
            });
        }
    }
});

That'll kick off the digest cycle, and you'll see the update happen as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.