Dynamic directives in angular

When the scope is changed, the attributes of the directive do not change; they still retain 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 on the first 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>'
    };
});
+5
source share
3 answers

Having defined scope: {}in your directive, it creates isolated scope. Thus, the parent area is now invisible from the directive.

, scope: true scope ( ) . , $scope.foo , , .

+8

:

  • 'scope:...' explicit scope: false - . , . , , , , , , , , /.
  • scope: true - , , . , , , , , - - .
  • scope: { ... } - "" - ​​ . , (.. {...}) , , , .
    • '=' scope - scope .
    • '@' . . .
    • '&' / .

, .

( ) . : / AngularJS?

+8

As Mark Rycock said, scope: {} will create a new isolated area that does not inherit properties from the parent, but we can still access these properties using the $ parent property.

Controller:

app.controller('indexController', function($scope) {
    $scope.test="Hello world!";
});

Directive

app.directive("test", function() {
    return{
        restrict: "A",
        scope: {},
        controller: function($scope){
            console.log("directiv $scope.$parent.test: " + $scope.$parent.test);
            console.log("directiv $scope.test: " + $scope.test);
        }
    };
});

output:

directiv $scope.$parent.test: Hello world!
directiv $scope.test: undefined
0
source

All Articles