2

I'm trying to add authentication capabilities to my app by providing a service auth with login and logout methods and a loggedIn property (once I get it to work, this will actually be the user object, but now it's just a boolean for simplicity) and a login directive, which displays either an inline login form or a logout button, depending on the value of the loggedIn variable.

Simple auth implementation:

app.factory 'auth', ($log) ->
  {
    loggedIn: false
    login: (username, password) ->
      $log.log "Login: #{username}, #{password}"
      if username is "a" and password is "b"
        @loggedIn = true
    logout: ->
      @loggedIn = false
  }

(Obviously, once I get this to work, the login will be done through REST! This is just for convenience, and all the app logic resides on the server, which uses a traditional session)

I'm having trouble with the directive. I know that I can use template or templateUrl to choose a template statically, but how do I replace the current template with a new $compiled one?

app.directive "login", ($compile) ->
    restrict: "E"
    templateUrl: "/login.html"
    scope: { }
    controller: ($scope, $element, $log, auth) ->
      $scope.auth = auth
      $scope.$watch 'auth.loggedIn', (newVal, oldVal) ->
        $log.log "Done: #{newVal} <- #{oldVal}"
        # here I should switch to the other template if newVal != oldVal

I know I could probably get the root element of the template, remove the old nodes and add the new ones, but I am hoping there is a more "declarative" way to do this in angular, without doing any DOM operations.

BruceBerry
  • 1,166
  • 1
  • 9
  • 21
  • i got it to work by following the example here: http://jsbin.com/unidoy/1/edit. replace the element using $element and then call $compile on the new subtree. However, I don't know if there is any extra precaution to be taken when replacing the old nodes with the new ones, in terms of bindings/watchers still alive on the old nodes. also, while the DOM manipulation logic here is minimal, technically I'm still manipulating the DOM :-) – BruceBerry May 08 '13 at 04:27
  • do you know replace:true property? – Ajay Beniwal May 08 '13 at 05:17
  • that doesn't seem to be related. it simply removes the `login` node when attaching the compiled template to the DOM. It has nothing to do with how compiling a new string is affected, and it doesn't seem you can pass this to $compile, but only as a directive definition option. – BruceBerry May 08 '13 at 16:36
  • Strugling with the same thing. I think the answer is a link function which has access to scope, and can then $watch the change in your variable. Check this answer, then adapt. http://stackoverflow.com/a/19122382/162070 – Zlatko Jan 20 '14 at 21:21

0 Answers0