Creating an Angular 1.5 component that utilizes ng-model

Can ng-model be used with a component in Angular JS 1.5.6? I am trying to bind a scope variable to a component using ng-model. If you'd like to see my issue, check out my Plunker. Specifically, I want the component "my-input" to be bound to the userData.name variable from the scope.

I am working with Angular JS 1.5.6 components and prefer not to use directives.

<body ng-controller="MyCtrl">
  <div class="container">
    <h2>My form with component</h2>
    <form role="form">
      <div class="form-group">
        <label>First name</label>
        <my-input placeholder="Enter first name" ng-model="userData.name"></my-input>
      </div>
    </form>
  </div>
</body>

Answer №1

Here is the code snippet you can utilize:

function customInputCtrl($scope) {
    var vm = this;
    this.$onInit = () => {
        this.ngModel.$render = () => {
            vm.data = vm.ngModel.$viewValue;
        };
        $scope.$watch(function() { return vm.data; }, function(value) {
            vm.ngModel.$setViewValue(value);
        });
    };
}
module.component('customInput', {
    require: {
        ngModel: '^ngModel'
    },
    template: '<input ng-model="vm.data"/>',
    controller: customInputCtrl,
    controllerAs: 'vm'
};

Answer №2

I have updated the Plunker for your convenience.

Make sure that the names of your parameters match the names in your component. Use camelCased names in your component and kebab-cased names in your templates. For example:

  bindings: {
      myPlaceholder: '@',
      myModel:'='
    }

 <my-input my-placeholder="Enter first name" my-model="userData.firstName">

In response to your question about using ng-model - you can use any parameter as long as you define it in your component. In this case, the parameter should be named ngModel.

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 trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Issue encountered: Unable to locate the file "SignInScreen" within the directory "./src/screens/authScreens" as referenced in the file "App.js"

App.js: import { StyleSheet, Text, View, StatusBar } from "react-native"; import { colors, parameters } from "./src/global/styles"; import SignInScreen from "./src/screens/authScreens/SignInScreen"; export default function A ...

What is the best way to retrieve variables from child components within a parent component in React?

I'm currently diving into React by working on a form/calculator application. I've come to realize that React follows a unidirectional pattern, and I'm struggling with how to deal with it. My goal is to create a table where users can input i ...

Utilizing CORS domain cookies in an AngularJS and Spring Boot collaboration application

As I work on developing an application using AngularJS 1.6 (http://localhost:8000) and Spring Boot (http://localhost:8080), I encounter an issue when trying to retrieve a cookie set by the Spring Boot API upon user login. Despite adding the cookie successf ...

Web API - Unable to retrieve resource: the server returned a status code of 404

Currently, I am working on an AngularJS project with Web API integration. One of the controllers I have is called Controller/MasterController, and this is configured in my WebApi Config: HttpConfiguration config = new HttpConfiguration(); config.Routes.M ...

Understanding the functionality of app.listen() and app.get() in the context of Express and Hapi

What is the best way to use only native modules in Node.js to recreate functionalities similar to app.listen() and app.get() using http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype.get = function(call ...

Flatpickr will refresh the list of days once a day is selected, causing any modifications made using onDayCreate to be reverted

After creating a Vue.js component that displays a customized calendar with different background colors for days, I encountered a problem. Whenever I select a day, all my customizations are lost because Flatpickr redraws the DOM elements for the days. How c ...

Determine the scrolling progress within a DOM element

My application requires content to be loaded as the user scrolls down, similar to social media platforms like Twitter and Facebook. I am currently working on detecting the need to load more data based on scroll events and the current position of the scrol ...

ExpressJS looping back

After exploring and practicing the creation of Rest APIs with both Loopback and ExpressJS individually, When using Loopback: I found it to be quite time-consuming to go through all the documentation and learn about loopback-specific features. However, i ...

What's the best way in Angular 6 to set focus on an element that's being made content editable?

I am currently utilizing the contentEditable attribute in Angular 6 to allow for editing the content of elements within an ngFor loop. Is there a way to focus on a tag element when its contentEditable attribute is set to true? <div class="tag" *ngFor= ...

How can I retrieve the chosen value of JQuery Chosen from the backend?

Is it possible to dynamically populate a select value from C# code using jQuery Chosen? I have successfully populated my select, but the issue is that it always returns the first item instead of the selected one. Here is how my select is declared: <s ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Challenges encountered when creating scenarios using Protractor

Up until that day, I always conducted individual small tests. However, now I want to run them in a single scenario, and I encountered a strange error. Some tests are unable to work together. For instance: First test: beforeEach(function(){ browser.get ...

Utilizing Bootstrap Modal to Upload an Image

I'm facing an issue with uploading an image using a Bootstrap modal. The problem I encounter is that even after selecting an image, I continue to receive the validation error message "Your upload form is empty". Below is the script for my form in the ...

Is it possible for a web server to transmit information without being prompted by the client?

I'm looking to create a web application for a tool that can run anywhere from a minute to a couple of hours. I want users to be able to initiate the tool's run directly from the webpage, and receive real-time status updates as the process progres ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

Having trouble locating the 'EJS' Typescript for the Express framework

After attempting to implement EJS with TypeScript, I encountered an issue where I am able to use res.send without any problems. app.set('views', path.join(__dirname, 'src/views/')); app.set('view engine', 'ejs'); ...

Leverage TypeScript Enum along with PropTypes to declare the properties of a React component

Upon having the Component and utilizing a TypeScript Interface for defining its props: interface Props { headerType: DROPDOWN_MENU_TYPE, //DROPDOWN_MENU_TYPE is enum headerContent: SVGClass isReverse: boolean; }; const MyComp: React.FunctionC ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

Organizing Angular project folders with the help of Node.js and Jade

I've been exploring different folder structures to ensure scalability as my project grows. While I found some useful resources, such as this one, I'm still struggling with how to actually implement these suggestions. Currently, I've adopted ...