Tips for synchronizing $scope between a directive and controller in Angular

Below is a directive that I have:

app.directive('fileInput', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        element.bind('change', function () {
            $parse(attrs.fileInput)
            .assign(scope, element[0].files)
            scope.$apply();
        });
        scope.$watch('files', function () {
            console.log(scope.files);
        });
    },
    controller: function ($scope, $element, $attrs) {
        $element.bind('change', function () {
            $parse($attrs.fileInput)
            .assign($scope, $element[0].files)

            $scope.$apply();
        });
        $scope.$watch('files', function () {
                console.log($scope.files);
            });
    }
}

EDIT and this is the controller:

controllers.controller('RegisterCtrl', ['$scope', '$routeParams', '$location', '$http', 'Restangular', 'ServiceRepository', 
function($scope, $routeParams, $location, $http, Restangular, ServiceRepository) 
{
   $scope.regService = function () {
        $scope.error = {};
        $scope.submitted = true;

        var fd = new FormData();
        fd.append("model", angular.toJson($scope.services));

        console.log($scope.files);
   }

}

This is the view file:

<input type="file" id="boarding-picture_where_sleeping" class="form-control" file-input="files" multiple>

Additional information: regService() method is called when submitting the form.

When debugging $scope.files, it's available in the console tab. However, in my controller, it shows as undefined.

How can I synchronize it between the directive and controller? Thank you.

Answer №1

Everything's up and running smoothly! Turns out the issue was due to me using two nested directives. Appreciate the help, team!

Answer №2

When creating a directive, it's advisable to include the scope and bindToController attributes in the definition. Take a look at this code snippet from a blog post about AngularJS best practices:

app.directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    controller: function () {
      this.name = 'Pascal';
    },
    controllerAs: 'ctrl',
    bindToController: true,
    template: '<div>{{ctrl.name}}</div>'
  };
});

Additionally, using the controllerAs syntax is recommended over passing around $scope for clarity and avoiding prototypical inheritance issues. This practice is endorsed by John Papa's AngularJS Style Guide.

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

Sequenced jQuery promises with the ability to halt execution

Currently, I am in the process of writing API code that involves multiple layers of wrapping around $.ajax() calls. One crucial requirement is to allow users to cancel any request, especially if it is taking too long. Typically, canceling a request can b ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Library for implementing stylish font effects in JavaScript

I remember stumbling upon a unique JavaScript library that enabled users to write text in different styles and formats. Unfortunately, I am having trouble finding it again. Can anyone suggest any helpful links? Thank you, Murtaza ...

What is the best way to determine the node version for executing the ng build command?

My current setup involves having two different versions of Node installed - 11.6 and 13.6. The default node version in the path variable is set to 13.6v. However, I have a project that specifically requires building with version 11.6v. Despite this, when u ...

Variable scope fails to update upon selection change

I'm currently setting up a select dropdown with an ng-options. The dropdown is appearing correctly on the HTML page, but for some reason, when I choose an option, the variable specified by ng-model is not updating in $scope. This is the HTML code: &l ...

Simple getJSON inquiry - why does the second parameter frequently go unnoticed?

I'm brand new to the world of Javascript, Jquery, and all that comes with it. I've been diving into trying to wrap my head around the getJSON function -- according to the documentation, it states: jQuery.getJSON( url [, data ] [, success ] ) ...

Implementing a multi-level 'Add More' feature with jQuery

I am trying to create a dynamic "Add more" button feature using jQuery. Although I managed to implement the functionality, unfortunately, it is not successful as there are several bugs and logical issues present. My requirement is to have an "Add more" b ...

How can a comparison value be utilized to retrieve a specific value from an array of objects?

I have an array containing several objects: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] Within this array, there is a specific id value that I am searching for. The id value I am looking for is "c2a6e78d2bc34cffb08d6e17a5631467" My objective ...

Deprecated as it may be, I am still determined to add an array of routes to my Vue router

In my Main.js file, I am currently fetching routes from the database using an API call. However, I've run into an issue with Vue router version 4 deprecating the addRoutes functionality. Now, I can only add one route at a time which is not ideal for m ...

Implementing re-render logic for a React functional component based on changes in useState()

I've created a basic functional component that retrieves a date from localStorage and displays it. The component includes two buttons to add or remove weeks from the date, expecting the updated date to be shown. However, I'm facing an issue where ...

Working with HTTP Requests in Node.js

Having a good understanding of how HTTP requests work, I am able to send and receive responses. Below is an example code showcasing an HTTP request: var http = require('http'); var options = { host: 'www.nodejitsu.com', path: &apos ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

Potential `undefined` Object Error Encountered with Optional Chaining in TypeScript

Currently, I have a response that I am retrieving from: data?.currentOrganization?.onboardingSteps?. It is possible for data, currentOrganization, and onboardingSteps to be null. My goal is to create a variable like this: const hasSteps = data?.currentOrg ...

SVG polyline animation that persists seamlessly

In my TypeScript code, I have implemented a function that creates a polyline based on 4 different points (x1y1, xCy1, xCy1, x2y2), where Xc represents the half distance between x1 and x2 on a plane. This polyline does not form a circular shape. private cre ...

The transformation of a class-based component into a functional one is proving to be ineffective

I am attempting to transform my class-based component into a functional one, but I am struggling with passing two parameters in one onClick function without relying on set state. Additionally, I want to avoid creating multiple extra functions as it would i ...

Can someone explain the intention behind using the code snippet {...rest}? I already understand how the three dots spread notation works in React Javascript

I already understand what the three dots spread notation in React Javascript does, so no need to explain. I have been learning ReactJs Javascript and reading code, and I recently came across this CodeSandbox example Within the code, there is: https://i ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

Error: Invalid jQuery syntax, expression not recognized

There seems to be a syntax error with an unrecognised expression: #2015-11-30|1112|1 I'm trying to add a class to an anchor tag with the Id of '2015-11-30|1112|1', similar to how I've done it with another element that worked fine. How ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

What steps can I take to prevent the audio from disappearing while utilizing `Tone.PolySynth()` along with the `Sequence` method?

Background I've been experimenting with creating a step sequencer using Tone.js. Instead of the traditional method of playing MP3 files with "Players," I decided to use "PolySynth" to achieve different sound variations, inspired by Jon Oliver's ...