Harry
Harry

Reputation: 54939

angularjs scope bindings and rootscope

I have some elements I want to only show the author of the document.

I can do something like this:

<div ui-show="currentUser == doc.user">Edit</div>
<div ui-show="currentUser == doc.user">Review</div>

Which is fine but because in my production code the ui-show is much longer than this example I don't want to copy and paste it everywhere that I need it.

I want to set a single variable that'll dynamically update as users log in and out or as the document gets updated with new / different users.

<div ui-show="isUser">Edit</div>
<div ui-show="isUser">Review</div>

Upvotes: 2

Views: 136

Answers (2)

DigitalZebra
DigitalZebra

Reputation: 41473

You have a couple of options to solve this problem:

1) Introduce a "global" or "parent" controller to your application. This will contain your isUser scope variable that you can basically set from any controller beneath this controller. Meaning that you can have a LogInController which will handle log off/in and can set that variable via $scope.isUser = false.

Here is a fiddle with an example of what this might look like: http://jsfiddle.net/digitalzebra/MrQrX/

2) Load different templates or includes based on whether or not the user is logged in/off. when using <ng-include src="partialTemplate"> the src attribute is actually an expression. So, you can toggle what template is actually loaded based on the value of that expression. You can then set the value in your controller and dynamically change which template is loaded: $scope.partialTemplate = "loggedOff.html"

Upvotes: 0

Harry
Harry

Reputation: 54939

I found that I could make isUser into a function.

<div ui-show="isUser()">Edit</div>
<div ui-show="isUser()">Review</div>

And write the conditions in the controller.

Upvotes: 2

Related Questions