Presenting validated material using Angular.js

app.controller('PageCtrl', ['$scope', '$stateParams', '$state', 'USER_ROLES', 'AuthService', function($scope, $stateParams, $state, USER_ROLES, AuthService){
  //console.log("Page Controller reporting for duty.");

  $scope.currentUser = null;
  $scope.currentUserExists = false; //<- defined in scope of PageCtrl
  $scope.userRoles = USER_ROLES;
  $scope.isAuthorized = AuthService.isAuthorized;

  $scope.setCurrentUser = function (user) {
    $scope.currentUser = user;
    $scope.currentUserExists = true; //<- set true here!!
  };

I am currently implementing the following in my HTML code:

<body ng-app="myApp" ng-controller="PageCtrl">

....

<div class="navbar-brand" ng-if="currentUserExists">Welcome!!</div>
<div class="navbar-brand" ng-if="currentUser.data.teacher._id">Welcome2!!</div>

I have experimented with using ng-show, and I'm testing both examples above to verify functionality.

When logging currentUser within my JS file, everything seems to be working correctly. However, nothing is displaying on my page. Am I overlooking something??

The structure of currentUser is defined as follows:

$scope.login = function (credentials) {
    AuthService.login(credentials).then(function (user) {
      $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
      $scope.setCurrentUser(user);
      console.log("currentuser");
      console.log($scope.currentUser.data.teacher._id); //Yes its working...
    }, function () {
      $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    });
  };

...

 authService.login = function (credentials) {


    return $http({
      method: 'POST',
      url: 'proxy2.php',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
      },
      data: {
        url: 'http://teach.classdojo.com/api/dojoSession?_u=tid',
        login: credentials.login,
        password: credentials.password,
        type: 'teacher'
      }
    }).success(function (res) {
        alert("login success");
        Session.create(res.teacher._id, "admin");
        return res.teacher;
    }).error(function (res) {
        alert(res.error.detail);
    });

  };

Answer №1

Consider giving this a shot:

<div class="header-brand" ng-show="userIsLoggedIn==true">Hello there!</div>

Answer №2

Your issue might stem from assigning a primitive value directly to the scope variable.

Instead, consider utilizing view.currentUserExists by initializing $scope.view as {currentUserExists: false} and then changing it to true when the promise is resolved.

Answer №3

The issue with the scope not functioning on the page was puzzling to me at first, leading me to consider whether it was due to inheritance or possibly caused by using $scope in multiple controllers.

To resolve this dilemma, I implemented a solution utilizing a service:

$scope.login = function (credentials) {
    AuthService.login(credentials).then(function (user) {
      userService.setCurrentUser(user); //<----This line was added
      $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);

    }, function () {
      $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    });
  };

...

 var updateUser = function() {
   scope.view.currentUser = userService.getCurrentUser();
 };
 scope.$on(AUTH_EVENTS.loginSuccess, updateUser);

..

app.service('userService', function() {
  var currentUser = null;

  return {
    setCurrentUser: function(user) {
      currentUser = user;
    },
    getCurrentUser: function() {
      return currentUser;
    }

  };
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting the character count binding in an AngularJS form: The ultimate guide

Within my angular view, I have implemented multiple form fields that display character counts as the user types. I have a button or link that is meant to reset all of the form fields and character counts. However, after clicking the reset button, the form ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

Enhance text by hovering over it

I am currently working on implementing a unique feature using jQuery and CSS. Rather than just inheriting the width, I want to create a magic line that extends to the next index item. Scenario: 1: Hover over Element one ELEMENT ONE ELEMENT TWO ELEM ...

Best practices for working with Angular, Laravel 4, and managing MySQL databases

I have recently started working with Angular and have some experience using Laravel 4. I am currently developing an application that allows users to edit on the go while also saving to a MySQL database. Originally, my plan was to use Angular for real-time ...

The element.find() function is experiencing issues when utilizing a templateUrl within a directive

My aim is to apply focus on an input field using a custom directive within a form. Initially, everything was functioning correctly when utilizing the template property in the directive. However, upon transferring the template into a separate HTML file usin ...

Having trouble accessing the property 'prototype' of null in Bing Maps when using Angular4

I'm currently working on creating a Bing component in Angular 4, but I'm facing issues with rendering the map. Below is my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title> ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

Display validation messages when the user either clicks out of the textbox or finishes typing

Here are some validation messages: <form name="dnaform" novalidate> <div style="padding-bottom:5px" ng-show="dnaform.uEmail.$pristine || dnaform.uEmail.$valid">Active directory account </div> <div style="padding-bottom:5px;" n ...

Achieving Vertical Centering of Text in Bootstrap 5 Buttons with Flex Box to Prevent Overlapping Icons

How can I prevent the text on a Bootstrap 5 button with horizontally and vertically centered text, along with a right aligned icon, from overlapping when it wraps? Additionally, how do I ensure that the icon stays vertically centered when the button text w ...

I am currently attempting to find a color picker element within a parent class using Cypress CSS Locator. While I am able to reach the parent element, I am unsure of the correct method to target the

My user interface has a list of elements displayed in 2 columns. The first column shows the name of the item, such as Manager, Operator, and the list is expected to grow. The second column consists of a color picker element where you can choose a color. I ...

The $.get route is failing to execute on the server-side, resulting in no data being retrieved. The server is not logging any information about this

I'm facing an issue where the $.get method is no longer working for me. I have simplified my code as much as possible, but it still doesn't work. Here is the code snippet: $("#test").click(function() { console.log("I'm in the on click e ...

Guide to dividing a string and structuring it into an array

I need help breaking apart these strings: var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.' var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.' to create an array like this: joh ...

Why isn't the Angular function being activated by the HTML generated by the datatable?

{ sTitle: "ANSWER_CORRECT", mData:"ANSWER_CORRECT", sClass: "readonly", mRender: function(data, type, obj) { ...

The clarity of an HTML input field is still unclear despite attempting to clear it using the clear()

When I created a form in HTML using PHP, AJAX, JavaScript, and jQuery, I encountered an issue where after entering data and updating it in the database, the input fields were not being cleared. I tried using clear() in JavaScript but it didn't work. C ...

Personalized Owl Carousel - OWL.JS Hover Pause Feature

I have been working on a slider in Codepen that is functioning well, and now I am trying to tweak it for my website. My goal is to make the carousel pause when someone hovers over it. I've experimented with all the options available on the owl slider ...

Utilizing jQuery for cloning elements

I need to add functionality for adding and deleting rows in multiple tables on my website. Currently, I am doing this by directly inserting HTML code using jQuery, but it has become inefficient due to the number of tables I have. I am considering creating ...

Angular offers a range of search filters for optimizing search results

The system currently has 3 search fields: 1. Name.... 2. Subject.... 3.Price.... Each of these filters works independently - when searching by name, only results matching that name are displayed; similarly for subject and price. However, the challeng ...

Guide to effectively utilizing addEventListener for images

Is it possible to measure the width of an image loaded by user click in Javascript? I need the width in order to adjust the position of a button next to the image. Here is the code I am using: document.getElementById('preIMG').addEventListener( ...

Calculating minutes per hour during a specific date range using JavaScript

What is the method to create an array representing minute counts per hour within a specified date range? If we have the following dates: const initial = new Date('2019-04-04 12:14'); const final = new Date('2019-04-04 16:21'); How ca ...

Encounter an error parsing the package.json file. Confirmed that it is valid JSON

As I embark on creating my very first yeoman generator, I have encountered an issue when running yo to initiate the project. The error message I am receiving is as follows: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! a ...