The bidirectional functionality of ng-model is not working as expected in my specific application

UPDATE: It seems that setting the controller in the view like

ng-controller="SomethingController as Ctrl"
and then using it in the model ng-model="Ctrl.myModel" actually works. How surprising!

I have been wanting to integrate this particular directive into my application. All I need to do is add my model as an attribute of the element with ng-model="myModel", and it should function correctly. I've seen it work in examples and even made it work on jsfiddle.

However, for some reason, it just won't work in my app. I've installed it through bower, included all the necessary files in my index.html, and injected it using

angular.module('myApp', ['angular-input-stars'])
.

The issue now is that the model only seems to work one way in my application. The ng-model="myModel" displays the correct number of stars based on the value of `myModel`, but when I change the stars (within the directive), that new value is not being sent back to my model.

I've looked at the code of the directive, and they are indeed using the model controller to set the value:

function link(scope, element, attrs, ngModelCtrl) {
    //...

    scope.setValue = function (index, e) {
         //...
        ngModelCtrl.$setViewValue(scope.last_value);
    }    
}

Even though the directive does not explicitly include scope: {ngModel: '='} in the return statement, this still works in examples and jsFiddle. However, I'm still unsure about the $setViewValue method, even after researching it further.

I suspect it may be related to the architecture of my application, although I can't be certain. The app is very well-structured and complex, and unfortunately, I cannot share the code due to company policies. However, I can explain how we have structured it:

|-- app.js (contains directive module, shown below)
|-- index.html
|-- /modules
      |-- /something
            |-- /overview
                  |-- somethingController.js 
                      (included in index.html & loaded through directive)
                  |-- somethingDirective.js
                      (included in index.html & loaded through app.js module)
                  |-- somethingView.html
                      (loaded through directive)

app.js code:

var app = angular.module('myApp', [
    'angular-input-stars',
    'something.overview'
]);

somethingDirective.js:

var somethingOverview = angular.module('something.overview');

somethingOverview.directive('somethingOverviewDirective', function () {
    return {
        restrict: 'E',
        controller: 'SomethingOverviewController',
        templateUrl:     'modules/something/overview/somethingOverviewView.html',
        scope: {
            overview: '=overview',
            errors: '=errors'
        }
    };
});

somethingController.js:

var somethingOverview = angular.module('something.overview', []);

somethingOverview.controller('SomethingOverviewController', 
    ['$scope', function ($scope) {
        function init() {
            $scope.myModel = 5;
        }

        // ...

        init();
    }]);

somethingView.html:

<div>
    Rating: {{myModel}}
    <input-stars max="5" ng-model="myModel"></input-stars>
</div>

Answer №1

As mentioned by @charlietfl in the comments, the issue lies in the direct scope of the primitive value

Here is the code snippet without using controllerAs:

<div ng-app="myApp">
    <h3>Greetings</h3>
    <div ng-controller="MyCtrl">
        Hello, {{name}}!

        <div>Rating: {{rating}}</div>

        <input-stars ng-model="rating.value" max="5"></input-stars> 
    </div>
</div>


app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.rating = {
        value: 5
    };
    $scope.name = 'Superhero';

}]);

To access the updated jsFiddle, click on the link below:

https://jsfiddle.net/14f05jdb/3/

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

Having received a status code of 200 in Flask WebApp, I am still unable to access the page

Currently in the process of developing a webapp using Flask, I have created the homepage where users are required to input their phone number and password. Once entered, the system will send an OTP to the provided phone number. When clicking the signup bu ...

How can you customize the bottom and label color for Material-UI TextField when in error or when in focus?

I need to customize the color of my Material UI TextField component for the following states: error focused Currently, I am using version 3.8.1 of @material-ui/core and working with the <TextField /> component. I would like to achieve this withou ...

Is it possible to omit a specific file from a GET request when utilizing angular?

As a newcomer to the world of Angular, I embarked on a project to deepen my understanding. My goal is to utilize a Pokemon API to display sprites that correspond with their respective names. However, I've encountered an issue where certain numbers in ...

Unable to process response from the $.ajax API POST request

Having an issue calling a REST API from my login page when clicking on a button. I am using $.ajax to make the POST request, and the backend shows a 200 code response. However, in the browser network tab, it displays as failed. The response from the API is ...

Exploring the process of iterating through a JSON response in PHP to extract all values

{ "ver":2, "inputs":[ { "sequence":4294967295, "witness":"", "prev_out":{ "spent":true, "tx_index":372805487, "type":0, "addr":"3AFgA1pHKrk4jFHwzUL1CKgZvXyFSWZfgD", "value":12712, ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Identify the activation of the "Inspect Element" feature

On Samy Kamkar's personal website at , there is a clever feature that detects when the console is opened and automatically clears the source code/console. It's a fascinating display of coding magic! https://i.stack.imgur.com/kag6U.jpg Curious t ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Exploring jQuery's Array Iteration Feature

Is there a way to create Custom Lists with a User-Friendly approach? For example: var unitA = []; unitA[0] = "Unit A One"; unitA[1] = "Unit A Two"; unitA[2] = "Unit A Three"; var unitB = []; unitB[0] = "Unit B One"; unitB[1] = "Unit B Two"; unitB[2] = " ...

Tips for incorporating filtering and sorting functionality in a API-focused application using React and Next.js

In my current project, I am developing a React application using Next.js. The main goal is to fetch data from an API and display cards based on user-selected filters. Specifically, I aim to retrieve the cards initially and then filter them according to the ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

The Selenium driver's execute_script method yields no result

One of the tasks I have is to determine if a specific element is within view. If it is, I want the script to return True; otherwise, False: driver.execute_script('window.pageYOffset + document.querySelector(arguments[0]).getBoundingClientRect().bottom ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Guide to obtaining the mouse click/touch coordinates within a specified container

Looking to obtain the x and y coordinates of a mouse click event within a relative container? There are numerous discussions on this topic on stackoverflow, such as jQuery get mouse position within an element. I attempted to convert the event.pageX and eve ...

Help me figure out how to independently toggle submenus on my navbar by utilizing the Vue.js composition API

I am currently working on developing a navbar using the Vue.js composition API. My primary objective is to toggle the submenus when a user clicks on them. However, since I am iterating through an object to display the submenus, I am faced with the challeng ...

The appearance of HTML dropdown select options is unappealing when viewed on iPhones

Looking for a simple alternative to the dropdown menu implementation on iPhones/iOS for a mobile website (not native app). Any suggestions using HTML/CSS/JavaScript? <!DOCTYPE html> <html> <head> <meta name="viewport" content="initi ...

What could be causing my mvc ajax to not locate the action?

I have implemented a button to trigger an API action using $ajax call. However, the API is not being called at all and I am only getting a fail message when the button is clicked. Can someone help me identify what I am missing or doing wrong? Below is th ...

A clever way to transfer the "HTML SELECT VALUE" to a different webpage using ajax without the need to refresh the page

Having trouble sending a selected value to another webpage without refreshing? I tried using ajax but couldn't get it to work. After the alert, it seems to stop functioning. Here's the script in one file, where I'm trying to send values 0, 2 ...

Is there a way to make the directional light illuminate only one half of the sphere in Three js (R3F)?

I'm trying to achieve a lighting effect on a sphere using two directional lights. One light is positioned in front of the sphere to mimic sunlight, while the other is placed towards the back to represent city lights. I'm experimenting with differ ...