How can I pass an Angular parameter to an onclick function?

Let's dive in... I am dealing with a controller

    $scope.selectedScript = {};
    $scope.selectedScript.scriptId = null;   


    $scope.selectScript = function(script, index) {
                    $scope.selectedScript = script;
                    $scope.selectedRow = index;

                    myAppFactory.updateTextArea(script).success(
                            function(data) {
                                $scope.selectedScript = data;
                            });
                };

    $scope.getSelectedClass = function(script) {
                    if ($scope.selectedScript.scriptId != undefined) {
                        if ($scope.selectedScript.scriptId == script.scriptId) {
                            return "selected";
                        }
                    }
                    return "";
                };

I have crafted an html page

<label>Script ID:</label> 
<input name="scriptId" 
       type="text" 
       id="scriptId"
       ng-model="selectedScript.scriptId" 
       ng-disabled="true"
       value="{{selectedScript.scriptId}}" /> 

thanks to IARKI, I now have this

<script type="text/javascript">
function goTo (){
 var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
 location.href=this.href + '?scriptId='+param1; 
 return false;
}
</script>
<a href="http://localhost:8080/DSS-war/debug.html" target="_blank" onclick="goTo()">Debug</a>

I also have a list of scripts in a table

<table class="scripts" name="tableScript" arrow-selector>
            <tr bgcolor="lightgrey">
                <th>Script ID</th>
                <th>File Name</th>
            </tr>
            <tr
                ng-repeat="s in scripts | filter:searchField | orderBy:'scriptId'"
                ng-click="selectScript(s, $index)" ng-class="getSelectedClass(s)">
                <td>{{s.scriptId }}</td>
                <td>{{s.fileName }}</td>
            </tr>
        </table>

Upon clicking the above link, a new tab opens, but the link remains as

 http://localhost:8080/DSS-war/debug.html

However, I want it to open in a new tab and look like this:

 http://localhost:8080/DSS-war/debug.html?scriptId=1
 http://localhost:8080/DSS-war/debug.html?scriptId=2
 http://localhost:8080/DSS-war/debug.html?scriptId=12

and so forth... with different numbers

any suggestions?

It needs to be with the onclick function, not the ng-click I know how it functions with ng-click, but I need to make it work with onclick...

and now, I am encountering this error from the chrome debugger:

Uncaught TypeError: Cannot read property 'scriptId' of undefined

at this line

var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;

Answer №1

If you want to access the angular scope using pure javascript, you can try the following code snippet:

<script type="text/javascript>
   function goTo (){
     var param1 = angular.element("#scriptId").scope().selectedScript.scriptId;
     location.href=this.href + '?scriptId='+param1; 
     return false;
   }
</script>
<a href="http://localhost:8080/DSS-war/debug.html" target="_blank" onclick="goTo()">Debug</a>

Note: This code may not be very useful, but it could provide some assistance.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>My Application</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<label>Script ID:</label>
<input name="scriptId" type="text" id="scriptId" ng-model="selectedScript.scriptId" ng-disabled="true">
<button onclick="generateID()">Set Code</button>
<a href="#" onclick="goTo()">Debug</a>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
    function generateID() {
        var code = Math.floor(Math.random() * 20) + 1;
        document.getElementById('scriptId').setAttribute('value', code.toString());
    }
    function goTo() {
        var scope = angular.element(document.querySelector('#scriptId')).scope();
        scope.$apply(function () {
            scope.selectedScript.scriptId = document.querySelector('#scriptId').getAttribute('value');
        });
        scope.changeURl();
    }
    angular.module('myApp', [])
        .controller('myCtrl', function ($scope, $window) {
            $scope.selectedScript = {};
            console.log('We are in controller');
            $scope.changeURl = function () {
                $window.open('http://localhost:8080/DSS-war/debug.html?scriptId=' + $scope.selectedScript.scriptId, '_blank');
            }
        });
</script>
</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

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...

Using i18next to alter language in a React app

Implementing the i18next translation system into my React app was a breeze thanks to a helpful guide I found. However, I'm facing an issue with changing the language manually. The guide covered the setup process perfectly, but lacked information on ho ...

How can a function in one React component be invoked from another component?

Currently in my React project's App.js, I am calling the this.searchVenues() function in my return statement. It works, but the implementation is messy and I know there must be a more efficient way to achieve this. The searchVenues() function is locat ...

Is the image overlay experiencing a flickering issue?

Last time, none of the solutions seemed to work quite right with the project, so let me try asking the question in a slightly different way this time. Basically, I have an image that, when someone hovers their mouse cursor over it, a div appears (containi ...

How can nextJS leverage async getInitialProps() method in combination with AWS S3?

I'm currently facing a challenge with executing an s3.getObject() function within an async getInitialProps() method in a nextJS project. I'm struggling to properly format the results so that they can be returned as an object, which is essential f ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Setting the current date as the default in an input box using ng-it: a step-by-step guide

How do I automatically set today's date as the default in the input box using ng-it? Here is my Plunker I am simply looking to set today's date as the default in the input field using ng-it. Would appreciate it if you could check out my P ...

Displaying 'N/A' in the chart if the data is missing

I have a chart that displays data, but when data does not exist it shows "undefined%". https://i.sstatic.net/Fm3Tl.png Is there a way to remove the "undefined%" and simply display nothing on the graph if no data exists? Here is the code snippet: import { ...

Developing a custom library to enable Ajax capabilities in web applications

Currently, I am in the process of developing my own personal library. jQuery doesn't quite meet my needs, and I prefer having a clear understanding of what is happening within my code. Nevertheless, I'm encountering an issue with the ajax functio ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

Managing the vertical space within a nested accordion section

I've built a custom accordion component, but I'm encountering scrolling issues when trying to use nested levels within the accordion. I'd like to prevent scrolling inside the accordion section and instead have the page scroll below it. Any ...

Searching for text using JQuery autocomplete feature with results fetched from an external source

I am currently working on integrating an input field with autocomplete functionality using the Google Books API to suggest book titles based on user input. My framework of choice for this implementation is Django. So far, I have managed to achieve the fol ...

AngularJS creates a new window in your application

I have created two html pages named web.html and addroute.html. Both pages are built with bootstrap. The angularjs script includes two controllers: webctrl and addctrl. In web.html, there is a button that, when clicked, opens the addroute.html page. I am ...

What is the best way to transfer an object property to an event handler function for executing DOM manipulation tasks?

I am working on a React-rendered HTML page that displays a list of objects representing websites. I have successfully stored these objects in memory and can show them in a long list on the page without any issues. Recently, I added a button for each objec ...

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...