Can a ng_model reference be passed to a function within an angularjs environment?

Instead of writing the same function 6 times for different relationships between a select box and an input field, I want to pass the ng_model reference of the input to the ng-Change function of the select box. This way, when the select box is changed, the function can update the referenced model automatically.

Update

This is my current setup:

<select id="name_select" ng-model="name_model" ng-change="getAU_name(type_model,name_model)" ng-selected="name_model" ng-options="user.name as user.name for user in AU_model[type_model]" required></select>
<input id="description_input" ng-model="description_model" disabled></input>


$scope.getAU_name = function (type, name) {
    $.each($scope.AU_model[type], function (index, value) {

        if (value.name == name || value.description === name) {
            console.log("name= " + value.name + " description= " + value.description);
            $scope.description_model = value.name;
        }

    });

However, because I have 6 similar relationships, I want to avoid repeating the getAU_name function just to set the $scope.description_model.

In essence, I have multiple models like description_model, description_model_2, etc., that I want to update with the same function.

Answer №1

There is a more simplified approach that can be taken here. Instead of using the type_model variable in the function, you could simply pass in the user object. Additionally, you can eliminate the need for the loop in the controller altogether.

To streamline the process, consider creating a single description object to contain all 6 models.

<select id="name_select" ng-model="name_model" ng-change="getAU_name(user, name_model, 'model1')" ng-selected="name_model" ng-options="user.name as user.name for user in AU_model[type_model]"  required></select>
<input id="description_input" ng-model="description.model1" disabled></input>

$scope.getAU_name = function (user, name, model_name) {
    if (user.name == name || user.description === name) {
        description[model_name] = user.name;
    }
};

Answer №2

Is there a reason to pass the mode if it is already in your $scope?

You can achieve the desired result with the following code:

View:

<input ng-model="stuff" ... >
<a ng-click="mychange();">click</a>

Controller:

$scope.mychange = function(){
  $scope.stuff = "newValue";
}

UPDATE:

I now understand your requirement, and I believe creating a directive would be helpful. Here's an example of how you can approach this issue:

View:

<div ng-repeat="event in events" data-testd> 
    <span>{{event.title}}</span>  
    <a ng-click="clicky(event)">click</a>      
</div>

JavaScript:

app.directive("testd", function() { 
    return function (scope, element, attrs) {
        scope.clicky = function(event){
            event.title="yolo";             
        }
    }
});

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

I am interested in retrieving document information from Firebase

/* eslint-disable indent */ import React, { useEffect, useState } from 'react'; import { Alert, } from 'react-native'; import firebase from 'firebase'; // import { useIsFocused } from '@react-navigation/native'; im ...

extract data obtained from an AJAX call

I am working on an ajax request in my code: var rootURL = "http://localhost/myapp/api/api.php"; $.ajax({ type: 'GET', url: rootURL + '/favourites', dataType: "json", success: function(list) { }, error: f ...

How can I extract the text following specific characters in a string using JavaScript?

I'm attempting to extract everything following specific characters in a string. However, when I use the alert() function on my code, I am puzzled by why there is a comma preceding the extracted string! To see the working version, click HERE This is ...

Nesting promises is proving to be successful while Promise.all is currently not functioning as

My directive contains the following code structure: myApp.directive('myDirective', function(s1, s2, s3) { return { restrict:'E', link: function($scope,) { s1.then(function(data) { $scope. ...

What is the best way to update the content of a div using a variable within a function in AngularJS?

I have a dilemma with my HTML pages. The index.html page displays product information from a JSON file, and I want the details of a specific product to show up on detail.html when users click on it. Though an alert can display the details, the innerHTML of ...

Utilizing the HasMany - BelongsTo relationship in Ember.js with the RESTAdapter

Can anyone provide guidance on creating a has many belongs to relationship using RESTAdapter in EmberCLI? I am working on a project where a card (representing a Twitter user) can have multiple hashtags associated with it. Here are my model definitions: / ...

Node.js convention for naming error arguments in callbacks

It is worth noting that in many instances involving nodejs, the callbacks that handle error arguments are commonly referred to as err rather than error. A prime example of this can be seen when examining the documentation on error handling in Express, wh ...

The output of Javascript's Math.random() function is consistently yielding closely matching values

Recently, I've been facing an interesting issue with positioning elements using Math.random() to set their left and top coordinates when they have a position of absolute. Despite expecting them to be scattered randomly across the screen due to the na ...

Exploring the names of rooms in Socket.IO and the corresponding number of users present in each

Currently, I am in the process of developing a simple chat application with rooms using socket.io versions: "socket.io": "^2.1.1" "socket.io-client": "^2.1.1" I have come across some fundamental questions during my research that I have been unable to fin ...

What is the purpose of the assertEquals() method in JSUnit?

Currently, I am exploring unit test exercises with a HTML5/JS game that I created and JSUnit test runner. The simplicity of the setup impresses me, but I have noticed that even the documentation lacks a clear explanation of what assertEquals() truly does. ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

javascript: unable to modify currentTime in <audio> tag

Struggling to create a progress bar for my HTML5 audioplayer and implement a function to change the playing track's time by tapping. I opted to use input[range], but encountering an issue where the current play time does not update when tapping on the ...

alert the Q Promise progress within a Node.js environment

When attempting to utilize the Q Promise Progress feature, my code is designed to catch progress and resolve the Promise once progress reaches 100. Here is the specific code snippet: var q = require("q"); var a = function(){ return q.Promise(functio ...

Exploring the integration of video playback within an Angular-Bootstrap modal upon opening

When it comes to loading videos dynamically based on a scope array of resources, I currently have the following setup: this.open = function (size, resource) { var modalInstance = $uibModal.open({ templateUrl: 'playModal.html', ...

I am looking to reveal concealed buttons using JavaScript

I am currently working on a web page that includes a button to display more buttons upon hover. However, I am facing an issue where the hidden buttons do not appear when hovered over. I referred to this solution: . Can anyone provide guidance on why these ...

Exploring ways to enhance the appearance of a Sidebar Widget Navigation using JQuery

When creating navigational items with submenus, such as 'Primary Fees', I added an arrow for visual indication. To enhance user experience, I included an animation that rotates the arrow and highlights the Main Menu item in red upon hovering. Thi ...

Elevation in design ui component

I am having an issue with the height of a theme-ui component I embedded. Even though the console shows it correctly, it is displaying at 100% height. <Embed src={url} sx={{width: '800px', height: '400px'}}/> This embed is contain ...

Watching for changes in an object of arrays using Angular's $scope.$watch

$scope.testObj={}; angular.forEach(results, function (value,index) { $scope.testObj[index]=value.arr; console.log($scope.testObj[index]); console.log(index); $scope.$watch('testObj',function(newVal, oldVal) { console.log(newVal, o ...

Obtain module-specific members through programmatic means

When working on a browser, the code may appear like this: //retrieve all enumerable properties of `this` function globalMems() { var g = this; var ret = {}; for (var prop in g) { ret[prop] = g[prop]; } return ret; } In Node.js, this does ...