简体   繁体   中英

How to hide show in Angular

I am beginner in angular js

HTML

<div ng-app="myapp">
    <div ng-controller="maincontrol">
        <div ng-show="!vis"><a href="#/">show</a></div>
        <div ng-show="vis"><a href="#/contact">hide</a></div>
    </div>
    <div ng-view></div>
</div>

JS

var app = angular.module('myapp', ['ngRoute'])
app.controller('maincontrol', function ($scope) {
    $scope.vis = true;
     $scope.fun = function () {

        if ($scope.user == "home" && $scope.pass == "home") {
            console.log($scope.user, $scope.pass);
            $scope.vis = false;
        }
    }
})


app.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'home.html'
        })
        .when('/contact', {
            templateUrl: 'contact.html'
        })
});

and also i have two html pages like

home.html

<div ng-controller="maincontrol">
    <input ng-model="user"/>
    <input ng-model="pass"/>

    <div ng-click="fun()">
        click
    </div>
</div>

contact.html

<div>
    contact
</div>

my expectation is after entering home into user and pass. if i click 'click' i need to show 'show' label instead of 'hide'. pls help me.

Each controller has its own scope, when you wrote $scope.vis=false on fun(), you actually created a new variable on maincontroler1 scope. If you expected this variable to affect the view which is binded to maincontroler scope, it won't happen.

I suggest 2 options:

  1. You can use one controller for entire app (If you use same controller in two tags it will still create a new scope although it is the same controller) , this way the fun() method that was called from the first view will change the boolean in the single controller and will affect the second view. Please note when you use ng-view you will have to get the variable from the parent .

So I used this code:

$parent.user 
$parent.pass

Create this working plunker for you.

  1. Share the vis boolean between 2 controllers using a service. You can use this post for this option.
  2. You can also use reach parent controller scope from child controller, that can be done if ng-view will be nested in the outer controller. You can use this post for option 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM