Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-if in transcluded scope breaks scope inheritance

That fiddle illustrates the issue http://jsfiddle.net/LAqeX/2/

I want to create a directive that wraps a part of the page and hides it. And i would like to use ng-if to remove unnecessary bindings. But some black magic happens.

This is my preferable directive code.

app.directive('withIf', function(){
    return {
        restrict: 'E',
        scope: {
            title: '@'
        },
        transclude: true,
        template: '<div>' +
        '<p ng-click="visible = !visible">{{title}}</p>' +
        '<div ng-if="visible" ng-transclude></div>'+
        '</div>',
        link: function(scope){
            scope.visible = false;
        }
    }
});

It is supposed to create two scopes:

  1. Directive isolate scope which has two variables - title and visible
  2. Transcluded scope which prototypically inherits from "regular" scope tree.

However, ng-if makes transclued scope somewhat detached from reality and trasncluded scope does not inherit from controller. Please, see the fiddle, it illustrates the issue very clear.

Any ideas what is happening there and how to solve it?

UPDATE

It seems i have figured out reasons why scope chain looks broken. The scope created by ng-if belongs to withIf directive isolate branch. So it never knows that controller's scope even exists. But the question remains the same - how to use ng-if in such case.

like image 562
Eugene Kostrikov Avatar asked Mar 03 '14 06:03

Eugene Kostrikov


2 Answers

ng-if creates a child scope, use $parent to access variables from parent scope. But in your case I would consider using ng-show or ng-hide instead of ng-if (they don't create child scopes)

like image 55
przno Avatar answered Nov 06 '22 17:11

przno


This bug seems to be fixed in Angular 1.3 - https://github.com/angular/angular.js/pull/7499

like image 34
VitalyB Avatar answered Nov 06 '22 18:11

VitalyB