4

Conditionally applying an element is easy - just use ng-show. But what about an attribute?

IE

<div ui-sortable>
  ...
</div> 

needs to be sortable only for admins, so do something like...

<div ng-conditional-attribute=" {'ui-sortable': 'user.isAdmin()'} ">
  ...
</div>
Robert Christian
  • 18,218
  • 20
  • 74
  • 89

3 Answers3

2

Create a custom directive or template and switch between the version with sortable attached and the version without.

ProLoser
  • 4,616
  • 2
  • 16
  • 23
  • This is definitely a good solution. But in the interest of DRY, looking for something that uses less code. – Robert Christian Mar 11 '13 at 02:04
  • Whatever route you take, you'll fundamentally have to write a new directive. You COULD just use `ui-if` on 2 variations, but the children DOM would still be repeated. Create a custom directive and conditionally add the property. If the priority is higher than sortable it _should_ work fine – ProLoser Mar 11 '13 at 02:06
  • 1
    Okay. That's not too bad. Thank you. – Robert Christian Mar 11 '13 at 02:47
  • @ProLoser you mind giving an example of that? I would also like to have `
    ` if `admin` is truthy, and `
    ` if it is not. How would you write a directive to do that?
    – deitch Sep 24 '13 at 08:52
  • Anyone got a more up to date solution for this? Scratching my head!! – adaam May 31 '15 at 22:05
1

Since a lot of directives also work from class you might be able to use ng-class="{'ui-sortable': user.isAdmin()}".

I don't know enough about the angular-ui directives to know what restrictions they have

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • You know what, that's an interesting idea I didn't think about. There's no real reason I can think of that the restrictions should prevent use in classes. It might be worth testing. – ProLoser Mar 13 '13 at 18:21
  • After thinking about it (and a little more testing) I realized this won't work. The location of all directives is cached at compile time, and since this class isn't present at compile time, the directive is never binded – ProLoser Mar 13 '13 at 18:26
0

Late to the party but it may help someone:

ng-readonly ="" 

will set the attribute if the expression is truthy.

There are a number of other ng attributes that work this way.

Charles Hankey
  • 495
  • 1
  • 7
  • 22