4

I have the following code (see below). When I click on the button and select the file, data.myVar in the view remains unchanged. (Somehow I do see that $scope.data.myVar updates correctly while stepping through the controller). Why is this happening?

html excerpt (it is under under the controller below):

{{data.myVar}}

<input type="file" onchange="angular.element(this).scope().setRuleFile(this)" />

JS:

angular.module('myModule')
    .controller('MyCtrl', ['$scope', function ($scope) {

    $scope.data = {
        myVar: 'init'
    };

    $scope.setRuleFile = function(element) {
        $scope.data.myVar = 'changed';
    }

}]);
developer033
  • 24,267
  • 8
  • 82
  • 108
jazzblue
  • 2,411
  • 4
  • 38
  • 63
  • Well, it should work.. any errors in console? You could provide a simple demo that reproduces this. – developer033 Jul 13 '16 at 00:11
  • event is outside angular context so you need to tell angular to run digest – charlietfl Jul 13 '16 at 00:21
  • @charlietfl: this is just an excerpt from html file which is view template, didn't want to paste all the routing, etc. Thought I am missing some simple fact about onchange or "file" type. – jazzblue Jul 13 '16 at 00:27
  • 4
    use `$scope.$apply()` – charlietfl Jul 13 '16 at 00:28
  • @charlietfl: Still do not get it: which event is outside angular context?$scope.$apply() actually fixed the issue, thanks for that! – jazzblue Jul 13 '16 at 00:32
  • 3
    angular is not aware of `onchange` ... so if you modify scope use `$apply` so angular knows to run digest.. try `$scope.data.myVar = 'changed';$scope.$apply()` – charlietfl Jul 13 '16 at 00:33
  • 1
    @charlietfl, is correct. Check it: http://plnkr.co/edit/Qv8cDpUPD5OL1VXTRpKX?p=preview – developer033 Jul 13 '16 at 00:37

1 Answers1

3

It is less hacky to use a directive instead. Here is a similar question: AngularJs: How to check for changes in file input fields?

Community
  • 1
  • 1
AJ Meyghani
  • 4,389
  • 1
  • 31
  • 35
  • Although I found that Angular does not allow me to pass element from directive into callback that I define in the scope: Referencing DOM nodes in Angular expressions is disallowed! Expression: - so it did not work for me. – jazzblue Jul 14 '16 at 23:57