0

I know these kind of questions have been asked many time before but none of them working for me. I'm new to directive working, may be its lack of learning that I'm unable to resolve my issue.

I've a variable in directive that I need in controller but there's no way to pass that value. Here is my directive code

return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        image: '=ngModel',
        allowedTypes: '@accept',
        dimensionRestrictions: '&dimensions',
      },
      link: function($scope, element, attrs, ngModel) {
        element.bind('change', function(event) {
          var file = (event.srcElement || event.target).files[0];
          ngModel.$setViewValue(file, 'change');
        });
      };
     } 

I need file variable in controller but I don't know how to do this... I've tried this fiddle but its not working in my case.

Any Kind of help will be appreciated.

Naila Akbar
  • 3,033
  • 4
  • 34
  • 76
  • The best way to share variables/values between directives or controllers is to use a service. Create an angular service and set the value in it. Inject this service to directive and contorller and you have access to the variable in both – Ranjith V Oct 14 '16 at 09:40
  • how to do this? – Naila Akbar Oct 14 '16 at 10:00
  • How are you using this directive? It looks like you are creating a directive for an element that has both the `ng-model` directive and your custom directive. In that case the isolate scope of the custom directive will fight the scope of the `ng-model` directive. The `ng-model` controller expects sibling directives have no scope. – georgeawg Oct 14 '16 at 15:19
  • This link has an example with explanation https://thinkster.io/a-better-way-to-learn-angularjs/services – Ranjith V Oct 16 '16 at 05:13

2 Answers2

0

You can send a function from the controller to the directive where you can pass your file variable

See this Example , It'll work on your case

Community
  • 1
  • 1
amrdruid
  • 951
  • 13
  • 24
0

Try this:

return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
Jigar7521
  • 1,549
  • 14
  • 27