user2039598
user2039598

Reputation: 13

AngularJS passing data from a directive controller to another

I have a form, which with you can edit an image gallery, of course I've created a directive for it, like this:

galleryEdit.html

<div>
  <form ng-submit="submit()">
    <label>Headline:</label>
    <input type="text" ng-model="gallery.headline" placeholder="Enter headline here" value=""/>

    <label>channels:</label>
    <channelselect></channelselect>

    <input type="submit"/>
  </form>
</div>

So, galleryEdit has another directive channelSelect, which with you can select a channel (not only for galleries)

channelselect.html

<div>
  <select>
      <option value="{{channel.shortCode}}">{{channel.name}}</option>
  </select>
</div>

GalleryEdit has a controller, that passes data (called "gallery") for its directive, so its $scope has $scope.gallery property, which contains channel id: $scope.gallery.channel. Since channelselect has different controller, that has its scope, this gallery.channel cannot be seen from that scope. Is there any way to pass data from gallery to channel controller/directive ? Using $scope.$parent is not a solution, since channelSelect should not know anything where the data is coming from.

Upvotes: 1

Views: 8164

Answers (1)

Scott Baldwin
Scott Baldwin

Reputation: 422

You can set up bi-directional binding between your galleryEdit directive's scope and your channelselect directive's scope.

In your channelselect directive's definition, you can do something like the following:

directive('channelselect', [function () {
    ...
    scope: {channel: '='}
    ...
}])

This will create an isolated scope for your channelselect directive, and will let you use the channel attribute on your <channelselect> tag to set up a bi-directional binding to its parent scope.

So now you can do this in galleryEdit.html:

<channelselect channel="gallery.channel"></channelselect>

Now channelselect's $scope.channel will be bound to galleryEdit's $scope.gallery.channel.

See the Directive Definition Object section of AngularJS's Directives guide for more details on isolated scopes.

Upvotes: 6

Related Questions