fourth fourth - 1 year ago 66
AngularJS Question

Weird behaviour of my scope variables

I am new in this field and want to write a app, now I meet some problems. Here is a simple version of my code, what I want is the API only show

first. After I press
and press
the button shown should be only

Now, my scope variable doesn't work, two button show here. Could you modify it and tell me the reason? Please use the rootscope and scope and sc.logIn() if possible so that I can know how to write in this way. Thanks!


mainControl.$inject = ['$rootScope','$scope'];
function mainControl($rootScope,$scope){

signUpControl.$inject = ['$rootScope','$scope'];
function signUpControl($rootScope){

Answer Source

There are couple of issues with your code.

Whenever you declare a module without a second argument, it just tries to fetch the module that is already declared / defined. In order to create a new module, you need to pass in the dependencies or an empty array, if there are no dependencies.

Also, you need to watch on the changes being done to the scope to ensure your changes are notified to the controllers to make them visible on the view.

Here is the working solution:

angular.module('myApp', ['myApp.dashboard', 'myApp.signUp']);

angular.module('myApp.dashboard', []).controller('mainControl', mainControl);

function mainControl($rootScope, $scope) {
  $rootScope.logged = false;
  $rootScope.$watch(() => $rootScope.logged, function() {
    $scope.logged = $rootScope.logged;

mainControl.$inject = ['$rootScope', '$scope'];

angular.module('myApp.signUp', []).controller('signUpControl', signUpControl);
signUpControl.$inject = ['$rootScope', '$scope'];

function signUpControl($rootScope) {
  this.logIn = function() {
    var a = 1;
    $rootScope.logged = true;
<script src=""></script>
<div ng-app="myApp">
  <div ng-controller="mainControl as mc">
      <div ng-hide="logged">

        <button type="button" class="btn" data-toggle="modal" data-target=".signUp">Sign Up</button>
      <div ng-show="logged">
        <button>Sign Out</button>

    <div class="signUp modal fade" id="signUp" ng-controller='signUpControl as sc'>
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">sigh up</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">&times;</button>
          <div class="modal-body">
            <form id="signUpForm" name="signUpForm" ng-submit="sc.logIn()">
              <label for="email">
                <input type="email" name="email">
              <button class="submit" id="signUpSubmit" type="submit" value="signUp">submit</button>
          <div class="modal-footer">


For some reason the code snippet doesnt let me submit the form.

You can find a working solution here : Codepen

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download