Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change template in ng-include on ng-click

Im trying to load different template after user authenticated him self in same place where login form were. Ill probably figured out the problem, i think its because i am not working in same scope.

i have a property in scope named template which i change on user successfully logged in there is a problem to this approach since if i call AccountCtrl again template will be overridden with login template again:

var AccountCtrl = WorkerApp.controller('AccountCtrl', function ($scope, $location, AccountService) {

    $scope.template = 'Home/Template/login';

    $scope.Login = function () {
                    $scope.template = "Home/Template/register";
            };
        };
    }    
});

in my index.html i have some html outside of ng-view:

    <div class="container">
    <div class="header">
        <div class="loginView">
            <div ng-include="template" ng-controller="AccountCtrl"></div>
        </div>
    </div>
</div>

and my login template

  <form name="login" ng-controller="AccountCtrl">
        <button class="btn btn-primary btn-sm" ng-click="Login()">Login</button>
    {{template}}
</form>

Im quite new to Angular, and cant figure out which way will be the angular way to solve this problem. in my template i could remove ng-controller="AccountCtrl" but then i cant call to login function in controller (I've tested that).

like image 359
Timsen Avatar asked Nov 02 '22 08:11

Timsen


1 Answers

Keep track of whether the user is authenticated using the root scope and then you can just hide/show partial depending on that boolean.

angular.module('myApp', []).run(function($rootScope) {
  $rootSCope.isAuthenticated = false;
});

var AccountCtrl = WorkerApp.controller('AccountCtrl', function ($scope, $location, AccountService) {
  $scope.Login = function () {
    $scope.$root.isAuthenticated = true;
  };
};

var AuthenticatedCtrl = function() {
  // Whatever you want to do once authenticated.
};

And then:

<div class="container" ng-show="isAuthenticated">
  <div class="header">
    <div class="loginView">
      <div ng-include="Home/Template/register" ng-controller="AuthenticatedCtrl"></div>
     </div>
  </div>
</div>

<form name="login" ng-controller="AccountCtrl"
  ng-hide="isAuthenticated"
  ng-include="Home/Template/login">
  <!-- The template should include a button that calls $scope.Login, obviously. -->
</form>
like image 124
Joe Avatar answered Nov 12 '22 10:11

Joe