Angular does not select the variable_name within the $scope

Here is the HTML code I have written.

<div class="container" ng-app="mintcart">
    <div class="panel panel-default" ng-controller="categoriesctrl">
    <input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/>
        <div class="panel-body">
            <div class="row">
                <ul class="nav nav-pills">
                    <?php
                    $i = 0;
                    while($i < count($list)){
                        $name = $list[$i]['categoryName'];
                        $id = $list[$i]['id'];
                        $normalUrl = $list[$i]['normalImageUrl'];
                        $hoverUrl = $list[$i]['hoverImageUrl'];
                        if($i == 0){
                            echo "<li role='presentation' class='active' ng-click='loadproducts($id)'><a href='#' >$name</a></li>";
                        } else {
                            echo "<li role='presentation' ng-click='loadproducts($id)'><a href='#''>$name</a></li>";
                        }
                        $i++;
                    }
                    ?>
                </ul>
            </div>
      </div>
   </div>
</div>

Additionally, here is my JavaScript code.

var app = angular.module('mintcart',[]);

app.controller('categoriesctrl', function($scope, $http){
    var auth = {};
    $http({
      method: 'GET',
      url: baseurl + 'api/get_product_categories'
    }).then(function successCallback(response) {
        $scope.categories = response.data.categories;
        // this callback will be called asynchronously
        // when the response is available
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });

    $scope.loadproducts = function(item_id) {
        alert($scope.session.sid);
        $http({
          method: 'GET',
          url: baseurl + 'api/get_items_in_category_cart/' + item_id
        }).then(function successCallback(response) {
            $scope.items = response.data.products;
            // this callback will be called asynchronously
            // when the response is available
        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
        //$scope.Language = lang;
    }; 

});

However, whenever the loadproducts function is executed, the alert($scope.session.sid); displays as "undefined". I am unsure why my element is not being recognized. Any assistance on resolving this issue would be greatly appreciated.

Answer №1

When working with PHP, keep in mind that it runs on the server side. To set a variable using JavaScript, do so outside of the view.

In JavaScript, create a variable to store the content returned by PHP:

var sessionId = <?php echo session_id(); ?>;

You can then access this variable in your controller:

 var app = angular.module("MyApp", []);

app.controller("categoriesCtrl", function($scope) {
  $scope.session.sid = sessionId;
  console.log($scope.session.sid);
});

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

Having difficulty transforming a JSON string into a JSON object using Javascript

Currently, I am working on a hybrid mobile application using Angular. I have a string that is obtained from a $http.jsonp request and I am attempting to convert the response into JSON format. After checking the validity of the JSON at , it appears to be va ...

The function `open` is not a valid prop for the `Dialog` component

Upon clicking an icon, a dialog box containing a form should appear for either adding a tab or deleting a specific tab. I have utilized reactjs, redux, and material-ui for the components. While I am able to display the dialog box when the icon is clicked, ...

Error: Trying to access a property that is undefined (specifically referencing 'rendered') has resulted in an uncaught TypeError

As a newcomer to React, I'm attempting to create a headless WordPress application. However, when I fetch a post, I only receive the first value. After fetching the post, I save it in the state: componentDidMount() { this.setState({ lo ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

PHP project encountered an error stating: "Uncaught TypeError: Ajax is not a function"

I am in the process of configuring an apache server for a project using XAMPP, MySQL, and PHP 5.6 Unfortunately, it appears that there is an issue with how JavaScript has been referenced in the project, and I am unable to get it to function correctly (th ...

Using Node.js to instantly redirect users to a new page while also sending them important

I am currently working on building a basic server for HTML pages using Node.js. The issue I am facing is that when I go to (for instance) http://localhost:8080/someDirectory, the browser mistakenly treats someDirectory as a file (when in reality, it is int ...

Issue with alert not being triggered in browser when using HTML and JavaScript function

Just starting out with HTML and Javascript! I'm working on a simple program where users can input a card number, and the browser should indicate whether it is valid (between 13-16 digits) or not. The website looks great, but I'm not getting an ...

Assigning a Node.js exported function to a variable

Is there a way to save an exported function as a variable without executing it right away, in order to use Promise.all? I noticed that when I assign the function to a variable, it automatically runs. How can I prevent this from happening during assignment? ...

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

The value of "asp-route-id" is dynamically determined through the use of

Hey there, I’m looking to dynamically pass a value from "codeDrink" to my controller using "asp-route-id" and Ajax in my ASP.NET MVC project. This is how I am handling it in my view: <p> <a id="deleteLink" asp-action="Delete& ...

Determine the quantity of characters available in a contenteditable field

I have implemented a directive that allows me to input editable content inside a tag Recently, I made modifications to include a character counter feature. However, I noticed that when I add line breaks, the character count increases erroneously. In the ...

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

Leveraging the ng-model value in ng-if

I am currently working on a feature that involves checking if an entered idNumber exists in a table, and then adding a glyphicon to the corresponding row. One issue I am facing is figuring out how to access the ng-model="idNumber" from within ng-if. My a ...

Display alternative text dynamically

Trying to gain a deeper understanding of state in react, this is a perfect example to me. When I say dynamic, I mean displaying the output below instantly as it is entered in the form. class Demo extends Component { constructor(props) { super ...

Issue with Laravel: unable to send data through ajax requests

I have developed a custom jQuery plugin specifically tailored for Laravel to facilitate sending data via Ajax to the server. However, I seem to be facing an issue where no data is being sent successfully. When I use dd($request->all()) to inspect what h ...

What could be preventing this Javascript from executing?

Can anyone help me troubleshoot why the JavaScript code is not executing in this HTML file? The console isn't showing any errors. Any suggestions? <!doctype HTML> <html> <head> <title>ProjectShare</title> ...

Is comparing strings in JavaScript as efficient as comparing numbers?

Considering creating a JavaScript enum library involves deciding how to store the values, I'm at a crossroads. Should I opt for speed in comparison or prioritize readability during debugging by using strings or numbers? While objects are an option too ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

PHP Calculator with Dynamic Calculations

I need to create an order form that updates the tax and total automatically once a quantity is entered into the text box. Should I use PHP or JavaScript for this functionality? Let's assume, for instance, that the tax rate is 0.3% My requirements: ...