Any recommendations for updating input in a directive without relying on $broadcast?

I am currently facing an issue with my contact list on controller A. Whenever I select a contact, the contact's information gets broadcasted to controller B and also to the datepicker directive in controller B. Although this method works, I am wondering if there is a more efficient way to update the input on the datepicker directive?

app.directive('datePickerDirective', [function () {
    return {
        restrict: 'AE',
        require: 'ngModel',
        scope: {
            datepickerNgModel: '=',
            datepickerId: '@'
        },
        templateUrl: 'Content/app/directives/templates/DatePicker.html',
        link: function ($scope, element, attrs, ngModel) {
            $scope.$watch(function () {
                ngModel.$setViewValue($scope.datepickerNgModel);
                return ngModel.$modelValue;
            });

            $scope.$on('data-from-component-a', function (event, data) {
                $('#' + $scope.datepickerId).val(data.date);
            })
        }
    }
}]);

Answer №1

Instead of using events like $broadcast, I recommend utilizing a factory to manage data for your components. Without details about your datepicker and controllers, I've provided a generic example to demonstrate the basic approach.

> Transfer data between controllers using a factory - view demo fiddle

View

<div ng-controller="MyCtrl">
  <button ng-click="publishData()">
    Publish data
  </button>
  <button ng-click="resetData()">
    Reset data
  </button>
</div>
<div ng-controller="MyOtherCtrl">
  <my-directive my-model="data.getData()"></my-directive>
</div>

AngularJS application

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, myFactory) {

  $scope.publishData = function() {
    myFactory.publishData();
  }

  $scope.resetData = function() {
    myFactory.resetData();
  }
});

myApp.controller('MyOtherCtrl', function($scope, myFactory) {
  $scope.data = myFactory;
});


myApp.directive('myDirective', function () {
    return {
      restrict: 'E',
      template: '{{myModel}}',
      scope: {
        myModel: '='
      },
      link: function (scope, element, attrs) {
          scope.$watch('myModel', function (newValue, oldValue) {
            console.log(newValue);
            // $('#' + $scope.datepickerId).val(newValue);
          });
      }
    }
});

myApp.factory('myFactory', function() {
  return {
    contactInfo: '',

    publishData: function() {
      this.contactInfo = 'Sdfsdfsdf';
    },

    resetData: function() {
      this.contactInfo = null;
    },

    getData: function () {
      return this.contactInfo;
    }
  }
});

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 for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Getting the environment variable from Rails in your JavaScript: A guide

I am currently working on implementing a key system within my application. In the code I am using, there is logic that looks like this: $('.key-test-button').on('click', function(){ if ($('.key-test-input').val() === "MYK ...

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

The functionality of Vue.js checkboxes is not compatible with a model that utilizes Laravel SparkForm

I've configured the checkboxes as shown below: <label v-for="service in team.services"> <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/> </label> Although they are displayed correctly, the ...

Circular Dependency occurs when child objects are created using the AngularFire ObjectFactory

Implementing AngularFire, I have customized the object factories to ensure encapsulated data and enable specific functionalities, as outlined in the official tutorial. My data structure resembles the following: { 'articles': { ' ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

How to display content in separate divs using jQuery hover functionality

I'm in the process of creating my online portfolio by using bootstrap and jquery. I have a series of images arranged side by side with each other, and I want to make the description for each image appear when that specific image is hovered over. Each ...

Updating a ReactJS component based on the selected value

My code currently includes a select element that retrieves ID's from an API, followed by a table that displays data. When I define a state like this example: this.state = {value:23}; the table successfully displays data from I'm trying to achie ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

Modify the class's height by utilizing props

Using Vue 3 and Bootstrap 5, I have a props named number which should receive integers from 1 to 10. My goal is to incorporate the number in my CSS scrollbar class, but so far it's not working as expected. There are no error messages, it just doesn&a ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

What is the best way to rearrange an array in React?

I need help with manipulating an array of strings displayed in a list. Each string should have the ability to move up or down within the array. For example: const array = ["hello", "world", "cool"] moveUp("world", 1) // (moveUp: value:string, index: nu ...

A guide on encrypting the data of a file that is uploaded in Meteor.js

As a newcomer to Meteor and coding in general, I have completed tutorial projects and examples and now feel ready to start my own project. I want users to be able to select a file from their computer using an input field, read the contents of the file, and ...

What could be the reason behind my Javascript code returning "object object"?

I am a beginner with jQuery. I attempted to calculate the sum of items from my django views using jQuery. Here's what I have so far: $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); ...

Executing a task on a deconstructed item within a JavaScript object

function transformTitle (string) { return string.charAt(0).toUpperCase() + string.slice(1) } Looking to capitalize the title directly after destructuring in a single line. const { question } = this.props const { title, Question_uuid: questionUUID } ...

Locating function definitions in etags using Emacs

I find syntax check in js2-mode to be quite effective. However, there are times when I wish to name a function "delete" or "new" even though it may not be the best practice. Js2-mode often flags this as an error. Is there a way to use built-in keywords as ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...