theSOer theSOer - 26 days ago 10
AngularJS Question

ng-show is not working in index.html but with other view its works fine in angularJs

what i require is that the hrefs with btns should be shown on the login/signup view and should be hidden on the dashBorad view

index.html

<body>
<div class="w3-sidebar w3-light-grey w3-bar-block" style="width:20%">
<div ng-controller="loginCtrl">
<h3 class="w3-bar-item" >Menu</h3>
<a ng-href="#!/signUp" class="w3-bar-item w3-button" ng-show="btns">SignUp</a>
<a ng-href="#!/login" class="w3-bar-item w3-button" ng-show="btns">Login</a>
<a ng-href="#!/addEmployee" class="w3-bar-item w3-button" ng-show="temp">Add Employee</a>
<a ng-href="#!/userData" class="w3-bar-item w3-button" ng-show="temp">List of Employees</a>
<a ng-href="#!/logout" class="w3-bar-item w3-button" ng-show="temp" ng-click="func()">Logout</a>
</div>
</div>


loginCtrl.js

myapp.controller('loginCtrl', ['$scope','myservice','$localStorage','$location',function($scope,myservice,$localStorage,$location) {
$scope.myobj={};
$scope.btns=true;
$scope.login=()=>{
myservice.login($scope.myobj).then((response)=>{ //myobj contains email and password
if(response.responseCode===200){
alert("Login Successful")
$scope.btns=false;
$location.path('/dashBoard');
}
},
(err)=>{
console.log(err);
})
}


when i update the value of btns they are still visible on the view. Cannot find what is happening. I have not used parent-child views.

plnkr

Answer Source

Problem

Your problem is 2 instances of the same controller. Lets see what we have on start:

console.log($scope.$id);  // --> 2

However when we click login link, we recreate new loginCtrl controller with different id:

console.log($scope.$id);  // --> 6

So our view is bind to scope with id 2 but we work with id 6

Demo that demonstrates the issue (See console)

  • 1st instance in <div ng-controller="loginCtrl">
  • 2nd instance $routeProvider.when .... controller:'loginCtrl'

Solution:

Since we use loginCtrl as root controller remove loginCtrl controller from $routeProvider

 $routeProvider
  .when('/login',{
    templateUrl:'login.html',
    //controller:'loginCtrl' // we don't need it, it will create new scope
  })

Fixed Demo