gogachinchaladze
gogachinchaladze

Reputation: 1074

Angular Directive cannot access scope

I'm not well experienced in angular js and your help desperately!

I'm trying to create a tab navigation for angular based website.

Here is my html:

<body ng-app = "app">
    <div class="bottom-content-container">
        <form class = "tab-nav">
            <tab-nav nav = "popular"></tab-nav>
            <tab-nav nav = "recent"></tab-nav>
        </form>

        <div class="tab-content" ng-switch = "tab">
            <div ng-switch-when = "popular">
                Popular Images
            </div>
            <div ng-switch-when = "recent">
                Recent Images
            </div>
        </div>
    </div>
  </body>

And here is the js:

var app = angular.module('app', []);

app.directive('tabNav', function () {
  return {
    template : '<label> <input type="radio" ng-model="tab" value="{{nav}}" name = "tabnav" /><span>{{nav}}</span></label>',
    replace:true,
    scope:{
      nav: '@'
    }
  };
});

The thing probably is that I'm messing up the scopes, and the directive is not changing the "tab" variable, so nothing happens.

Here is the jsbin

Thanks in advance!

Upvotes: 2

Views: 514

Answers (4)

MayaLekova
MayaLekova

Reputation: 550

Another solution is to use $parent:

app.directive('tabNav', function () {
  return {
    template : '<label> <input type="radio" ng-model="$parent.tab" value="{{nav}}" name = "tabnav" /><span>{{nav}}</span></label>',
    replace:true,
    scope:{
      nav: '@',
      tab : '='
    }
  };
});

Also notice how the value property is bound.

Upvotes: 0

Mohsin Muzawar
Mohsin Muzawar

Reputation: 1212

<tab-nav ng-click="tab='popular'" nav = "popular"></tab-nav>
  <tab-nav ng-click="tab='recent'" nav = "recent"></tab-nav>

Upvotes: 0

gogachinchaladze
gogachinchaladze

Reputation: 1074

JSBIN

I found a solution ! Don't know what's the negative sides of it, but works fine !

I'm passing the tab to tab-nav and works nice (y)

Upvotes: 0

Alberto
Alberto

Reputation: 129

I've made a jsbin.

In the directive scope @ is used to bind to attributes, as your directive should set a selected value that will be read from outside you need to use =. Then I wrap everything insde a ctrl to hold this selected value so your content can use it to display the tabs.

Upvotes: 2

Related Questions