What is the best way to incorporate HTML and JavaScript into an Angular view?

Within my markup, there is a substantial chunk of code enclosed with ng-controller tags. The structure resembles this:

<div ng-controller="MyController">
    <script>
        // MyController is initialized with current_item_data to streamline data loading
        var current_item_data = <?= json_encode($this->view->current_item_data) ?>;
        var current_parent_item_data = <?= json_encode($this->view->current_parent_item_data) ?>;
    </script>

    <!-- large markup here -->
</div>

The challenge arises when I aim to reuse the same controller multiple times on one page, for instance:

<div>
    <div ng-controller="MyController">
        <script>
            var current_item_data = []; /* contains item #1 data */
            var current_parent_item_data = []; /* stores parent item #1 data */
        </script>
    </div>
    
    <div ng-controller="MyController">
        <script>
            var current_item_data = []; /* has item #2 data */
            var current_parent_item_data = []; /* retains parent item #2 data */
        </script>
    </div>
</div>

Within the initialization logic of MyController, the following is found:

app.controller('MyController', ['$scope', '$window', function($scope, $window) {
    
    $scope.currentItemData = $window.current_item_data;

    $scope.parentItemData = $window.current_parent_item_data;

}]);

As evident, each instantiation of MyController references the same global variable, leading to unexpected behavior.

I am seeking any workaround as immediate refactorization of the codebase is not feasible at present.

Answer №1

Avoid using <script> tags in your template. Instead, consider utilizing angular's ng-init directive:

<div ng-controller="MyController"
     ng-init="init(<?= json_encode($this->view->current_item_data) ?>, <?= json_encode($this->view->current_parent_item_data) ?>)">

</div>

In your controller:

app.controller('MyController', ['$scope', '$window', function($scope, $window) {

    $scope.currentItemData = [];
    $scope.parentItemData = [];

    $scope.init = function(currentItemData, parentItemData) {
        $scope.currentItemData = currentItemData;
        $scope.parentItemData = parentItemData;
    }

}]);

Answer №2

Another option is to utilize routeProvider, where you can assign controllers based on different pages. This method can help streamline your AngularJS application.

Check out the DEMO here

app.js

var app = angular.module('myModule', ["ngRoute"]);

app.config(function($routeProvider) {
    // setting up routing
    $routeProvider.when('/', {
        templateUrl : 'templates/dashboard.html',
        controller : 'mainCtrl',
        title : 'Home'
    }).when('/about', {
        templateUrl : 'templates/about.html',
        controller : 'AboutController',
        title : 'About'
    }).when('/contact', {
        templateUrl : 'templates/contact.html',
        controller : 'ContactController',
        title : 'Contact'
    }).otherwise({
        redirectTo : '/'
    });
});

html

<!DOCTYPE html>
<html lang="en" ng-app="myModule">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AD Operation Reports</title>


</head>

<body >
    <div ng-view></div>
</body>

</html>

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

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

Tips for linking server value with Javascript onmousedown in an aspx web page

I have a single Hyperlink on an aspx page. There are two tasks I need to accomplish: When I click on the hyperlink, I want to log some activity. While logging the EmployeeID value, I need to bind it from the server. However, I am encountering an error t ...

What is the proper way to structure the ng-options syntax in AngularJS?

I received an array from a REST service and I am attempting to generate a dropdown menu based on that data. Check out the jsfiddle example here $scope.reasons = [{ "languageLanguageId": { "languageId": 1, "lastUpdate": "2015-05-08T11:14:00+03:00" ...

Attempting to make a gallery image expand when clicked on

Having trouble with image expansion in a gallery when clicking on different images. Currently, the expanding feature only works on the first image in the set. If I click on another image, the first one is the one that expands. <div ng-repeat="album ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

Conceal a form depending on the referer_url parameter

I am looking to customize my 404 page by displaying a small form only when the visitor comes from a website, not from an email link or directly entering the URL. The purpose of this form is to address broken links that led the visitor to the error page. If ...

The unique format created by tinyMce is not being displayed

I am trying to customize the style format of my tinyMCE, but I am having trouble getting it to show up. Can anyone suggest what might be going wrong? Where should I place the button "Formats" so that I can choose a specific style? tinyMCE.init({ mod ...

Adjust the JavaScript variable upon pressing the "c" key

I'm trying to figure out how I can toggle the value of variable x in JavaScript when the key "c" is pressed. Specifically, I want x to change from 0 to 1 when "c" is pressed and revert back to 0 when it's released. I have already defined and name ...

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Observing input value in Popover Template with Angular UI

I am currently working on a directive that utilizes the Angular Bootstrap Popover and includes an input field. Everything seems to be functioning properly, except for the fact that the watch function is not being triggered. For reference, you can view the ...

Clone a specific link within a div using jQuery only one time

I have a group of divs and I want to copy the link from the first div and put it into the last div (mobile-link). Currently, it is either duplicating all the links and inserting them all at once, or if I use :eq(0), it's placing the first link in each ...

Stop unauthorized pages from hijacking login cookies

I have a website called where users can create their own HTML pages accessible through the link if the username is "USR" and project is "PROJECT". However, there is a security concern... Currently, I store users' login tokens as cookies. But what ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

The specified redirect_uri is not compatible with Facebook authentication for Ionic using Satellizer

I've been using the satellizer library for integrating Facebook authentication into my ionic app. While developing in the browser, I have configured the satellizer fb object as follows: $authProvider.facebook({ clientId: AppConstants.facebook.clie ...

A guide on utilizing radio buttons to delete specific rows within a table with the help of AngularJS

My current issue involves using radio buttons to delete rows in a table. The problem I'm encountering is that multiple rows are being deleted at once instead of just one. You can view an image of my table here. As we all know, with radio buttons, onl ...

Exploring the functionality of filtering cards using a search box in Bootstrap 5 and JavaScript

https://i.sstatic.net/VlD20.png I tried to bring the medicine I searched for to the top by clicking on the search button, but unfortunately it did not work. Can someone help me with writing the JavaScript code for this? <form class="form-inline ...

Requesting Axios.get for the value of years on end

I'm grappling with obtaining a JSON file from the server. The endpoint requires a year parameter, which needs to be set as the current year number as its value (e.g., ?year=2019). Furthermore, I need to fetch data for the previous and upcoming years a ...