Utilizing ngModel within the controller of a custom directive in Angular, instead of the link function

Is there a way to require and use ngModel inside the controller of a custom Angular directive without using the link function? I have seen examples that use the link function, but I want to know if it's possible to access ngModel inside the directive controller. The method I tried below returns undefined. Is there another approach to achieve this? I need to validate the component and apply the invalid class to the error object.

//directive
angular.module('myApp', [])
  .directive('validator', function (){
    return {
      restrict: 'E',
      require: {
           ngModelCtrl: 'ngModel',
           formCtrl: '?^form'
      },
      replace: true,
      templateUrl: 'view.html',
      scope: {},
      controllerAs: 'ctrl',
      bindToController: {
         rows: '=',
         onSelected: '&?' //passsed selected row outside component
         typedText: '&?' //text typed into input passed outside so developer can create a custom filter, overriding the auto
         textFiltered: '@?' //text return from the custom filter
         ngRequired: "=?" //default false, when set to true the component needs to validate that something was selected on blur. The selection is not put into the input element all the time so it can't validate based on whether or not something is in the input element itself. I need to validate inside the controller where I can see if 'this.ngModel' (selectedRow - not passed through scope) is undefined or not.
      },
      controller: ["$scope", "$element", function ($scope, $element){
         var ctrl = this;
         ctrl.rowWasSelected;

         //called when a user clicks the dropdown to select an item
          ctrl.rowSelected = function (row){
               ctrl.rowWasSelected = true;
               ctrl.searchText = row.name; //place the name property of the dropdown data into ng-model in the input element
          }

         ctrl.$onInit = $onInit;
         function $onInit (){
             ctrl.ngModelCtrl.$validators.invalidInput = validate;            
          }

        function validate (modelValue, viewValue) {
             var inputField = ctrl.formCtrl.name;
             var ddField = ctrl.formCtrl.listData;

             inputField.$setValidity('invalidInput', ddField.$touched && ctrl.rowWasSelected);

            return true;
          }          
       }];
   }
});

//template
<form name="validatorForm" novalidate>
  <div class="form-group" ng-class="{ng-invalid:validatorForm.name.$error.invalid}">
     <label for="name">Names</label>
     <input type="name" class="form-control" name="name" placeholder="Your name" ng-change="typedText(text)" ng-model="ctrl.textFiltered" ng-blur="ctrl.validate()" ng-required="ctrl.ngRequired">
  </div>
  <ul ng-show="show list as toggled on and off" name="listData" required>
    <li ng-repeat="row in ctrl.rows" ng-click="ctrl.rowSelected({selected: row}) filterBy:'ctrl.textFiltered' ng-class="{'active':row === ctrl.ngModel}">{{row}}<li>
  </ul>
</form>

//html
<validator
   rows="[{name:'tim', city:'town', state:'state', zip: 34343}]"
   on-selected="ctrl.doSomethingWithSelectedRow(selected)"
   typed-text="ctrl.manualFilter(text)"
   text-filtered="ctrl.textReturnedFromManualFilter"
   ng-required="true">
</validator>

Answer №1

After updating the code a bit, I realized that you might need to be using the latest version of Angular for some of these changes. Upon reviewing your question, it's unclear what specific issue you're facing, whether it's related to using 'required' in the directive definition object or utilizing the 'ngRequired' attribute. The code below eliminates the need for $scope:

angular.module('myApp', []);
angular.module('myApp').directive('validator', validator);

function validator (){
    return {
        restrict: 'E',
        require: {
            ngModelCtrl: 'ngModel'
        },
        replace: true,
        templateUrl: 'view.html',
        scope: {}, //this controls the kind of scope. Only use {} if you want an isolated scope.
        controllerAs: 'ctrl',
        bindToController: {
            rows: '=',
            onSelected: '&?', //pass selected row outside component
            typedText: '&?', //text typed into input passed outside for custom filter
            textFiltered: '@?', //text return from custom filter
            ngRequired: "=?" //default false, set to true for validation on blur
        },
        controller: 'validatorController'
    }
}

//usually do this in a new file

angular.module('myApp').controller('validatorController', validatorController);
validatorController.$inject = ['$element'];

function validatorController($element){
    var ctrl = this;

    //controller methods
    ctrl.validate = validate;

    ctrl.$onInit = $onInit; //angular will push this after all controllers have been initialized

    function $onInit() {
        if(ctrl.ngRequired)
            ctrl.ngModelCtrl.$validators.myCustomRequiredValidator = validate;
    }

    function validate (modelValue, viewValue){
        return rowWasSelected !== undefined
    }
}   

Here are some insights from Angular's docs on $compile:

If the require property is an object and bindToController is truthy, then the required controllers are bound to the controller using the keys of the require property. This binding occurs after all the controllers have been constructed but before $onInit is called.

and

Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before the controller constructor is called, this use is now deprecated. Initialization code relying on bindings should be placed inside a $onInit method on the controller.

Ensure you are using the latest Angular version for these features to work correctly. Previously, I encountered issues with compatibility on versions below 1.4.7.

Second Edit: Clarifying a few points:

1) The .ng-invalid class is applied to any invalid input in an Angular validated form. To add a red border after blur, use a CSS rule like this:

.ng-invalid.ng-touched {
   border: 1px #f00 solid;
}

2) $formatters format model values to view values and $parsers validate input values before updating model values.

3) Logic involving values bound to the controller via bindToController should be placed in $onInit. This includes ngModelCtrl.

4) To trigger validation only after blur, utilize ng-model-options or test for $touched in the validator function.

To access formCtrl, add formCtrl: '^form' to your require object.

Answer №2

To access the information provided by ngModel in a custom directive, the simplest method is to set the scope to false. While this should be the default behavior, explicitly setting it can be beneficial when working with multiple directives. By doing so, the directive will inherit the controller and controller alias as if it were a natural part of the view.

Here is an example of the directive:

.directive('myValidator', function (){
return {
  restrict: 'E',
  replace: true,
  templateUrl: 'view.html',
  scope: false
  };
}

You do not need to make significant changes to the template. Just ensure that the ng-model="ctrl.name" is binding to something on your main controller or the relevant controller for the rest of the view. You can also move the validation function to the main controller or a service and inject it into the controller.

Utilizing compile or link in a custom directive can enhance its versatility. These options allow you to pass values for directives, attributes, or HTML tags. While ngModel is accessible, you may not always use ctrl.user with every instance of the custom directive. Using compile or link enables you to set the value of ngModel each time the directive is used.

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

Tips on creating a responsive absolute div

I'm currently working on creating a profile component with Material UI and React.js. I'm having trouble making the Avatar/profile photo and profile name div responsive. Here are some screenshots to illustrate my issue: The specific div that need ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

Unlocking the power of bitwise operations in VueJS with Javascript

Forgive me if this sounds like a silly question. I'm currently using vue-moment within my Vue.js application and I have the following code snippet: <!-- date = '2020-03-23 01:01:01' --> <span>{{ date | moment('from', & ...

When the app loads in AngularJS, make sure to call the jQuery plugin. Additionally, remember to call

In my AngularJS app, I have a need to call the following code: $('.nano').nanoScroller({ alwaysVisible: true }); This should be executed when the application loads and also when the state changes. In traditional non-angular applications, I wou ...

The VueJS function is not defined

Looking for a way to fetch data from graphql in my vue project and store it in a variable. The function is asynchronous and the value of rawID needs to be awaited. However, there is a possibility that it could result in undefined, causing an error in the ...

Dealing with Errors using Restangular

I'm struggling with retrieving a JSON object from my backend using Restangular. 1) Everything seems to be working fine, but I am unsure how to handle errors since there is no callback or promise function: meals = restAngular.all('meal').ge ...

Turn off the ability to click on images, but allow users to access the right

https://i.stack.imgur.com/jriaP.png Example image sourced from reddit.com Illustration represents the desired effect using CSS and possibly JS. In essence: I aim to make an image on a website unclickable to its imageURL There should be a context menu ...

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

Is there a way to iterate through two arrays simultaneously in React components?

Recently delving into the world of React, I am utilizing json placeholder along with axios to fetch data. Within my state, I have organized two arrays: one for posts and another for images. state = { posts : [], images : [] ...

Challenges with the "//" syntax in UNIX

$('#lang_choice1').each(function () { var lang = $(this).val(); $('#lang_files').empty(); $.ajax({ type: "POST", url: '< ...

Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet. I have seen similar questions asked before, but I am puzzled as ...

Lack of Ajax query string parameters

To implement a functionality where clicking on a delete button in the UI triggers a service method that retrieves data from a database and displays it in a popup, I need to call a specific method in an Action class. The task id and command name (method nam ...

ng-pattern for requiring whole numbers only with no decimal points

Looking for an ng-pattern to limit the entry of decimals in an input type number field. I attempted using ng-pattern="/^[0-9]$/" but it doesn't display an error when entering values like 1.0, 2.0, 3.0, etc. Example: 2.0 = fail 2 = pass 3.0=fail 3=p ...

What is the best method for clearing all session cookies in my React application?

Currently, I am working on a project using React. I am trying to find a method to automatically logout the user by deleting all of the session cookies in my React application. However, I have not been able to come up with a solution yet. Is there a way to ...

Chrome's keyup event restricts the use of arrow keys in text fields

Could you please test this on Google Chrome browser: jQuery('#tien_cong').keyup(function(e) { jQuery(this).val(jQuery(this).val().replace(".", ",")); var sum = 0; var tien_cong = jQuery('#tien_cong').val(); tien_cong = tien_ ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

history.js - failure to save the first page in browsing history

I have implemented the history.js library to enable backward and forward browser navigation on an AJAX products page triggered by clicking on product categories. While I have managed to get this functionality working smoothly, I am facing a particular iss ...

It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...