Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic directives in angularjs

Tags:

angularjs

The directive's attributes don't change when the scope is updated, they still keep the initial value. What am I missing here?

HTML

<ul class="nav nav-pills nav-stacked" navlist>
    <navelem href="#!/notworking/{{foo}}"></navelem>
    <navelem href="#!/working">works great</navelem>
</ul>

<p>works: {{foo}}</p>

Javascript (based on angular tabs example on front-page)

angular.module('myApp.directives', []).
directive('navlist', function() {
    return {
        scope: {},
        controller: function ($scope) {
            var panes = $scope.panes = [];

            this.select = function(pane) {
                angular.forEach(panes, function(pane) {
                    pane.selected = false;
                });
                pane.selected = true;
            }

            this.addPane = function(pane) {
                if (panes.length == 0)
                    this.select(pane);
                panes.push(pane);
            }

        }
    }
}).
directive('navelem', function() {
    return {
        require: '^navlist',
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: { href: '@href' },
        link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
            scope.select = tabsCtrl.select;
        },
        template:
            '<li ng-class="{active: selected}" ng-click="select(this)"><a href="{{href}}" ng-transclude></a></li>'
    };
});
like image 374
user28061 Avatar asked Sep 19 '12 20:09

user28061


1 Answers

By defining scope: {} in your directive, it is creating a isolated scope. So the parent scope is now invisible from the directive.

If you want to refer the parent scope, then you can put scope: true for shared scope (among same directives) and omit the scope declaration for just normal scope nesting. Or if you want to just refer $scope.foo of the parent, you can define explicit scope variables like you've done in the child directive.

like image 181
Tosh Avatar answered Oct 16 '22 15:10

Tosh