Question

I have the following:

<div data-ng-controller="resultsController">
    <div id="DIV1" ng-include src="'views/sidebar.html'" ng-class="showSidebar ? 'open' : 'closed' "></div>
    <div id="DIV2" ng-class="showSidebar ? 'open' : 'closed' "></div>

And within ( ng-include src="'views/sidebar.html'" )^ i have the following div with ng-click which triggers the change of showSidebar

    <div class="panel-header top-sidebar" ng-click="showSidebar = !showSidebar; ">

$scope.showSidebar = true; is in the resultsController and when the ng-click is called the ng-class on DIV1 takes effect but doesn't on DIV2.

Any ideas?

Was it helpful?

Solution

There are two ways you can solve this:

1.Not a desired way

Using $parent to access the parent scope.

<div class="panel-header top-sidebar" 
     ng-click="$parent.showSidebar = !$parent.showSidebar; ">

We only need to access parent for a primitive type but not for an object. So:

2.Appropriate way

Appropriate way is to have the flag showSidebar inside a model object on scope lik.

$scope.someModel = { showSidebar: true }

and then refer it inside the included page because when you ng-inlcude, a new child scope is created off of the parent. But in this case, since you are referring to the object reference, the changes will be reflected in child as well as parent scope.

Here is a DEMO. Click on text "Inside" to see the change.

OTHER TIPS

ng-include creates its own $scope so your showSidebar doesn't propagate to DIV2 because it's outside it's scope. My advice: make a service for your sidebar. and include it in the right controller(s).

EDIT

You create a service called sidebar and inject it into your controller as such

app.controller('mainCtrl', ['$scope', 'sidebar', function($scope, sidebar){
    //track sidebar
    $scope.sidebar=sidebar;   
}]);

That way you can give your sidebar properties and methods that you can access in your views.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top