1

I have the following service:

 myapp.service('myService', function () {

      var familyList = this;
      familyList.people = [
        { name: 'Jax', dob: '01/01/1974', cell: '3035551212', carrier: 'ATT', email: 'jax@soa.com', active: true },
        { name: 'Tara', dob: '03/01/1974', cell: '3035551313', carrier: 'SPRINT', email: 'tara@soa.com', active: false }];

 });

I have the following directive:

  myapp.directive('applyplugin', function () {
      return {
          link: function ($scope, myService) {
              $scope.myService = myService;
              alert(myService.people.length);
              $("select[id^='ms']").each(function () {
                  $(option).remove();
              });
          }
      }
  });

Can I reference the familyList array from the directive?

webdad3
  • 8,893
  • 30
  • 121
  • 223

1 Answers1

1

Sure, but the service (dependencies) injection does not take place in the link function, but in the one definig the directive.

The code becomes:

myapp.directive('applyplugin', function (myService) {
    return {
        link: function ($scope) {
            $scope.myService = myService;
            alert(myService.people.length);
            $("select[id^='ms']").each(function () {
                $(option).remove();
            });
        }
    }
});

You cannot inject anything in the link function, its signature is fixed and is link(scope, element, attributes, ...requiredDirectives) {... } (you won't use the last parameter most of the times, it is for when you directive requires the use of another using ^someDir syntax)

NOTE: You probably want to use this element parameter in your link function to only affect elements that are within the directive: element.find("select[id^='ms']").each( ... )

floribon
  • 19,175
  • 5
  • 54
  • 66
  • thanks for this answer. Could you take a look at my other question to see if you can answer it? http://stackoverflow.com/questions/29382602/reloading-my-drop-down-when-using-a-custom-directive – webdad3 Apr 03 '15 at 20:53