简体   繁体   中英

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!

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.

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM