Navigating with Angular and Symfony

I am encountering some routing issues while using Symfony and Angular. I attempted to adapt this tutorial for my project with a Symfony backend. However, no matter what changes I make in my main HTML page or in my JS Angular files, when I inspect an element using Chrome tools, I always find that the div containing my ng-view is commented out. I have come across comments on forums suggesting that AngularJS will comment out ng-view if the routes are not functioning correctly. Can someone kindly assist me in resolving this routing problem?

EDIT: It appears that Angular can locate the route but is unable to retrieve the partial HTML because every HTML page called shows a 404 error in the console. Does anyone know where I should place my HTML partial files?

EDIT 2: I managed to find the path to my static HTML file, but when attempting to access it, the web server returns a 403 error (forbidden). Can anyone advise me on how to gain access to this file?

Below are the relevant files:

layout.html.twig (main template):

<!DOCTYPE HTML>
<html ng-app="adcApp">
    <head>
        <meta charset="utf-8">
        {% stylesheets filter='cssrewrite'
        'Resources/css/bootstrap.min.css'%}
            <link rel="stylesheet" href="{{ asset_url }}" type="text/css"/>
        {% endstylesheets %}
        {% javascripts
            'Resources/js/jquery-1.9.1.js'
            'Resources/js/bootstrap.js'
            'Resources/js/angular.js'
            'Resources/js/angular-route.js'
            'Resources/js/app.js'
            'Resources/js/Controllers.js' %}
            <script type="text/javascript" src="{{ asset_url }}"></script>
        {% endjavascripts %}
        <title>ADC-WebApp</title>
    </head>
    <body>
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" ng-href="">ADC-WebApp</a>
            </div>
            <div>
                <ul class="nav navbar-nav">
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="">Plan de production
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a href="#/Comparaison">Comparaison</a></li>
                            <li><a href="#/Param">Paramètres</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="row">
        <div ng-view></div>
    </div>
    </body>
</html>

app.js:

'use strict';

var adcApp = angular.module('adcApp', ['ngRoute', 'adcAppControllers']);

adcApp.config(function($interpolateProvider){
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}'); //Conflict with Twig
});

adcApp.config(['$routeProvider', function($routeProvider)
{
    $routeProvider.when('/OGPP/#/Comparaison',
        {
            templateUrl: 'partials/Comparaison.html',
            controller: 'ComparaisonCtrl'
        })
        .when('/OGPP/#/Param',
        {
            templateUrl: 'partials/Param.html',
            controller: 'ParamCtrl'
        })
        .when('/OGPP',
        {
            templateUrl: 'partials/index.html',
            controller: 'HomeCtrl'
        });
}]);

PHP Controller :

class OgppController extends Controller
{
    public function indexAction()
    {
        $content = $this->render('ADCOgppBundle:Ogpp:layout.html.twig');
        return new Response($content);
    }
}

My partial folder is located in the same directory as my layout.html.twig (BundleDir/Resources/Views/Bundle). All controllers are declared, but they only output text to the console without printing anything.

Answer №1

After some trial and error, I finally got it to work! As a newcomer to angularjs and Symfony, I'll share the steps I took to make my routes function properly.

1st : When dealing with routes in angular, avoid using /#/. Simply start your route right after this. Angular routes should begin after this URL segment. For more information, refer to this thread (look for the first answer).

2nd: In your angular templateUrl, be sure to include the full path starting from your project directory. For instance, if you are utilizing wamp (like me) and your project is named 'Symfony', then the path would be:

WampInstall/Symfony\src\projectName\BundleName\Resources\views\BundleName\partials
assuming you use partial as the directory name for your partial views.

3rd: Apache may block angularjs from making a GET request. To address this, you will need to make some configurations. I personally modified the .htaccess file within the .src Symfony directory. You can find guidance on this issue by following this link. However, keep in mind that altering server configurations may impact web server security.

Following these steps, everything should be up and running smoothly.

Answer №2

Typically, combining Symfony with Angular is not recommended as it can hinder the maintainability of your application. It's generally advised to keep your frontend and backend separate.

However, if you still wish to proceed with this approach, there are existing plugins available that can help with handling Symfony Routing in JavaScript.

To ensure Symfony and Angular work well together, one method is to wrap your Angular HTML in components to prevent conflicts with Twig. You can then pass your baseUrl to these components like so:

<componentName baseurl="{{ app.request.scheme ~ '://' ~ 
app.request.httpHost ~ app.request.basePath }}"></componentName>

Subsequently, utilize it in your templateUrl function:

templateUrl: function($attrs) {
                return $attrs.baseurl + 'templates/componentName.template.html';
            }

This solution may not be the most elegant but should suffice for making Symfony and Angular work in tandem.

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

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Remove an image that has been selected while uploading multiple images using AngularJS

If I want to delete a specific image from multiple uploads by clicking on the image in AngularJS, how can I achieve this? Each uploaded image has an associated textbox. When the delete icon on the image is clicked, both the image and the corresponding text ...

Retrieving JSON data and transforming it into HTML

After reading several examples, I am still struggling with a particular issue. I am receiving a feed from an API that is structured like this: { total:123, id: "1234", results: [ { id: "1234", name: "bobs market", ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

Utilize Jquery to locate and update the text of all div elements that have an empty id attribute

I need help with a task involving a list of divs, some with ids and some without. My goal is to identify all the divs within a specific class that have empty ids and change their inner text to say "no data available". Can this be done? My attempt using $( ...

Implementing event listener for component generated by mapping function

I am using the map function in Javascript to render a list, but I am struggling to add a click listener to the elements in that list. Check out the code here - https://codesandbox.io/s/oqvvr1n3vq My goal is to log Hello to the console whenever the h1 tag ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Testing components in Angular using Renderer2

Recently, I came across an Angular component with the following structure: constructor( @Inject(INJECTION_TOKEN_WINDOW) private window: Window, private renderer: Renderer2 ){} ngOnInit() { this.renderer.addClass(this.window.document.body ...

TypeScript maintains the reference and preserves the equality of two objects

Retrieve the last element of an array, make changes to the object that received the value, but inadvertently modify the original last position as well, resulting in both objects being identical. const lunchVisit = plannedVisits[plannedVisits.length ...

drawImage - Maintain scale while resizing

I am currently working on resizing an image using drawImage while maintaining the scale. Here is what I have so far... window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext(" ...

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

What is the process for triggering an event to initiate an action within a Node server or a websockets loop?

I'm currently delving into the realm of websockets using Node.js ws and Node mplayer in order to tackle a specific issue. At the moment, I have a straightforward websocket (ws) loop set up along with a fully operational mplayer instance. I am able to ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Unexpected error from API call detected within Mint localhost Template Kits elements

Hello Everyone, hope you're all having a good day! Recently, I installed the Elementor and Envato Elements plugins on my localhost Linux Mint WordPress setup. After configuring permalinks and other settings in WordPress, I proceeded to browse Templat ...

Preventing bots and spiders from infiltrating the ad network. Stepping up efforts to block unwanted traffic

We are facing a constant battle against bots and spiders with our in-house ad system, striving for 100% valid impressions. To achieve this goal, I conduct experiments on a specific ad zone that is only displayed on one page of our site. By comparing the G ...

Assigning an argument of type `any` to a parameter of type `Observable<IComboboxItem[]>` can be considered risky

I have a piece of code that retrieves data from the backend server. Here is the code snippet: @Injectable() export class DictionariesDatasourceFacadeService { public invoiceTemplate: IDataSource<IComboboxItem>; public replacedLegalEntity: IData ...

Implementing Jsplumb in Angular 2

Struggling to integrate Jsplumb with Angular2. Attempting to incorporate jsPlumb into an Angular2 component, but encountering an error stating jsPlumb.ready is not a function Added it via npm and placed it in my vendor.js for webpack Below is the compon ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...