Assign a new value to a controller scope variable without relying on angular.element in AngularJS

I have the following div:

<div ng-controller="MyController as MC" id="div1">                                                                                                                   
    <a href="#" id="1" ng-init="MC.EntityId = 1 , MC.EntityType = 57" ng-click="MC.LoadFiles(MC.EntityId, MC.EntityType)" title="Upload">Upload </a>                                                                                                         
</div>

Here, I want to display the EntityId and EntityType that I have set in div1.

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.EntityId}}, EntityType = {{MC.EntityType}}                                                                                                      
</div>

How can I set EntityId and EntityType for div2 within the LoadFiles function without using angular.element?

app.controller('MyController', function () {
  this.EntityId = 0;
  this.EntityType = 0;

  this.LoadFiles = function (id, type){
       this.EntityId = id;
       this.EntityType  = type;
  }
});

Answer №1

To maximize efficiency, consider developing a custom service that can be injected into multiple controllers. This service can handle the saving and retrieval of your data entities seamlessly.

Answer №2

In order to achieve two-way data binding, it is necessary to utilize an object rather than a primitive type. The following changes need to be implemented:

app.controller('MyController', function () {

  this.Entity = {EntityId:0,EntityType:0};

  this.LoadFiles = function (objEntity){
       this.Entity.EntityId = objEntity.EntityId;
       this.Entity.EntityType  = objEntity.EntityType;
  }
});

HTML :

<div ng-controller="MyController as MC" id="div1">
    <a href="#" id="1" ng-init="MC.Entity.EntityId = 1 , MC.Entity.EntityType = 57" ng-click="MC.LoadFiles(MC.Entity)" title="Upload">Upload </a>    
</div>

HTML Div2

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.Entity.EntityId}}, EntityType = {{MC.Entity. ntityType}}                                                                                                      
</div>

EDIT :

<div ng-controller="MyController as MC" id="div1">
    <a href="#" id="1"  ng-click="MC.LoadFiles(MC.Entity)" title="Upload">Upload </a>    
</div>

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.Entity.EntityId}}, EntityType = {{MC.Entity. EntityType}}                                                                                                      
</div>

Controller :

controller('MyController', function () {

  this.Entity = {EntityId:1,EntityType:57};

  this.LoadFiles = function (objEntity){
       this.Entity.EntityId = objEntity.EntityId;
       this.Entity.EntityType  = objEntity.EntityType;
  }
})

Check out the Plunker for more information.

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

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

Slick Slider - Defining the Initial Slide

My website features a dynamic carousel showcasing a basketball team's schedule, with games sorted by date for the current season. I am trying to align the slider to display the upcoming game at the center. How can I designate a specific slide as the ...

The statement ... is not a valid function, it has returned undefined

Currently experimenting with AngularJS, encountered an error message: Argument 'Controller' is not a function, got undefined View the JSFiddle link, along with HTML code: <h2>Hata's Tree-Like Set</h2> <div ng-app ng-init="N=3 ...

Show text upon hovering using jQuery

I am currently exploring jquery and trying to implement a functionality where text is displayed upon hovering over a div element. My basic html page consists of squares, with one of them rotating when a button is clicked. I now want to show some text withi ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

Having trouble importing my function component into a router in reactjs. Need some guidance on how to properly set it up

I am working on a Slider component function called export default Slider. In my App.js file, I have the following code: function App() { return ( <Router> <Routes> <Route exact path='/' element={<Home />} /> ...

What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right ...

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

Retrieve the accurate placeholder color using JavaScript

I modified the default placeholder color of my input to blue. How come I am seeing a black placeholder color when using JavaScript? const fetchPlaceholderColor = () => { let inputElement = document.querySelector('.myClass'); let inputEl ...

Utilize the power of modern Javascript to extract and display data from a JSON file by mapping an array and adding it

I've been attempting to construct a table from a JSON file by utilizing the map method in React. I've experimented with two approaches - one using map and the other using a for loop - but so far, I haven't been successful in getting the desi ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

Using JavaScript, verify if the user is connected to a network

Does anyone know of a simple method to verify if the user is able to access our website? Determine if they are not receiving a connection error. ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: https://i.sstatic.net/YN7Iu.png The HTML ...

Trouble in Cypress Automation: Unable to locate button using text-based search

Recently, I have been diving into learning Cypress and have spent the last few weeks automating different websites. However, I have encountered a challenge when trying to click a button based on its class or text value, which seems like it should be a simp ...

Determine the location of an image with the help of Jquery

I'm currently working on finding the position of an image with Jquery. The issue I am facing is that it only provides me with the initial position of the image when the document was loaded. $(".frog").click(function(){ alert($(".frog").position() ...

Steps to deactivate a textarea in angularjs based on a selected option's value meeting a specific condition

Hello, I am a newcomer to AngularJS and I am looking to disable the textarea when a specific option is selected from a dropdown menu. I attempted to use ng-disabled="(here my ng-model value)" but unfortunately, it did not work as expected. If creating a ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...