Search code examples
angularjsangularjs-ng-transclude

Controller $scope property does not change with expression in transcluded content


The problem is that when you have transcluded content which contains an expression as an attribute of ng-click for example, the change does not occur in the scope of the parent controller as you can see in this fiddle:

http://jsfiddle.net/vt7rmqya/

Nothing happens when you click hide box inside of transcluded content.

    <div ng-controller="myCtrl">
    <panel ng-show='showBox'>
        <div class='box'>
             {{name}}
            <br>
            <button ng-click='showBox = false'>hide box button inside of transcluded content</button>
        </div>
    </panel>
    <br>

Here, the expression in ng-click has no effect on the $scope.showBox in the controller but you would think that it would because the scope of the transcluded content should be the same as the controller scope, right?

BaseApp = angular.module('BaseApp', []);

BaseApp.controller('myCtrl', function($scope) {
    $scope.name = 'bill jones';

    $scope.showBox = true;
});

BaseApp.directive('panel', function() {
    return {
        restrict: 'E',
        template: '<div>header<br><div ng-transclude></div></div>',
        transclude: true,
    }
})

Solution

  • I realized that the solution is simply to set the ng-click attribute to a function in the controller instead of an expression like so:

    BaseApp.controller('myCtrl', function($scope) {
        $scope.name = 'bill jones';
    
        $scope.showBox = true;
    
        $scope.hideBox = function() {
            $scope.showBox = false;
        }
    });
    
    
    <panel ng-show='showBox'>
       <div class='box'>
          {{name}}
          <br>
          <button ng-click='hideBox()'>hide box button inside of transcluded content</button>
        </div>
     </panel>
    

    Here's the working fiddle:

    http://jsfiddle.net/75f2hgph/