Issues with retrieving the scope attribute within a directive

I am currently facing an issue where I am unable to access the values stored in $scope.photoRes within my directive. When I use console.log(scope.photoRes) in the directive, it only displays an empty object. Here is the output from the console:

Object {fileName: "db372ec33603208781eb6fbf9789c816a4ab27d2.jpg", filePath: "C:\wamp\www\skittlize\photo_assets\uploads\db372ec33603208781eb6fbf9789c816a4ab27d2.jpg"} SkittlesCtrl.js:17
Object {} SkittlesCtrl.js:37

'use strict';

angular.module('skittlesApp')
  .controller('SkittlesCtrl', function ($scope, $location){
    $scope.photoRes = {};
    $scope.dropzoneConfig = {
      'options': { // passed into the Dropzone constructor
        'url': 'photo_assets/save2.php'
      },
      'eventHandlers': {
        'sending': function (file, xhr, formData) {
        },
        'success': function (file, response) {
          $scope.$apply(function () {
            $scope.photoRes = JSON.parse(file.xhr.getResponseHeader("photoInfo"));
            $location.path('/uploader')
            console.log($scope.photoRes);
          });
        }
      }
    };
  })
  .directive('dropzone', function () {
    return function (scope, element, attrs) {
      var config, dropzone;   
      config = scope[attrs.dropzone];   
      dropzone = new Dropzone(element[0], config.options);   
      _.each(config.eventHandlers, function (handler, event) {
        dropzone.on(event, handler);
      });
    };
  })
  .directive('imgSwitch', ['PhotoServ', function (PhotoServ) {
    function link(scope, element, attrs) {
      scope.$watch('photoRes', function (newVal) {
        if (newVal) {
          console.log(scope.photoRes);
          var cropper = new CROP();
          cropper.init('.selfie-container');
          cropper.loadImg('/uploads/'+scope.photoRes.fileName);
          $('.cropButton').on('click', function () {
            PhotoServ.skittlize('/uploads/'+scope.photoRes.fileName);
          });
        }
      });
    };
    return {
      link: link
    }
  }]);

Could this issue be occurring because changes made in the parent scope are not being registered?

Answer №1

It is unlikely that scope[attrs.dropzone] is a valid expression as there seems to be no assignment of scope within the directive.

To resolve this issue, there are two possible solutions. One approach is to simply pass it as an attribute in your HTML code (assuming you are not already doing so).

<div dropzone photoRes="{{photoRes}}"> </div>

You can then access the value by calling attrs.photoRes.

The alternative option is to assign scope within the directive using @, =, or &. In this case, @ would likely be suitable for your needs as it fetches the value from an attribute. Remember that you still need to pass in your $scope as an attribute.

On the other hand, using = would create a 2-way data binding with a $scope object, which may be unnecessary in this context.

.directive('dropzone', function() {
    return {
        restrict: "A",
        scope: {
            photoRes: "@",

        },
        link: function(scope, element, attrs ) {
            console.log(attrs.photoRes);
            console.log(scope.photoRes);

    };
})

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

What causes offsetHeight to be less than clientHeight?

INFORMATION: clientHeight: Retrieves the height of an element, taking into account padding offsetHeight: Obtains the height of an element, considering padding, border, and scrollbar Analyzing the Data: The value returned by offsetHeight is expected to ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

Arranging an Array of Arrays Containing Strings

Looking for a solution to sort an array containing arrays of strings? A similar issue was discussed here. Here is the array in question: var myArray = [ ['blala', 'alfred', '...'], ['jfkdj', ...

Styling Angular Datatables with CSS

i have data on the front end https://i.stack.imgur.com/2xq7a.jpg i need all check marks to be displayed in green color. Below is the code snippet: $scope.dtColumnsCal= [ DTColumnBuilder.newColumn('name').withTitle('Name') ...

Refreshing the Span Element using Ajax and php

Hello there, Stack Overflow community! I have a basic PHP script (countsomething.php) that retrieves a number and displays it using echo. How can I use AJAX to automatically update a simple span element on my HTML page? I've attempted to trigger th ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

Transitioning between javascript functions

Having some issues with a switch case statement, also tried using if-else but no luck. In the HTML code: <select onBlur="functionCalc()" id="art"> <option value="hours" id="hours">Hours</option> <option value="minutes" id="mins">M ...

What is the best way to extract the singular PDF link from a webpage?

Currently, I am attempting to utilize Selenium in Java to access DOM elements. However, I have encountered an issue while testing the code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is n ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Navigating through the Table using AngularJS

I was able to successfully loop through a table using AngularJS to retrieve values from a specified scope named {{rec}} as shown below. HTML <div id="AngularContainer" data-ng-app="myApp" data-ng-controller="myCtrl"> < ...

Loop through the API URLs for AngularJS

$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) { $scope.website = data.websites; }); $http({method: 'GET',url: '/xx/xasxxx?websiteId='+$scope.website.websiteId}).success(function( ...

Mandating the inclusion of a directives controller in conjunction with other necessary controllers

Two directives are nested within each other, with one requiring the other using require: '^parentTag' . Both directives have their own controllers. In the parent directive, I can access its controller as the fourth argument in link: function(scop ...

Leveraging JavaScript to determine whether a number is even or exiting by pressing the letter "q"

The main goal is to have the user input a number to check if it is even, or enter 'q' to exit the program. var readlineSync = require('readline-sync'); var i = 0; while (i <= 3) { var num = readlineSync.question ...

Error encountered while attempting to install ungit on Windows XP: Unable to locate file directory in C:/Documents

Ungit seems like the ideal tool to gain a better understanding of git, thanks to its graphical interface that simplifies the process. I came across this video explanation which is very helpful in grasping how git functions, even if you don't intend to ...

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...

Setting up Angular 6 on Azure Platform

I am currently facing challenges while trying to deploy a sample application on the azure portal. To start off, I decided to run some tests by creating an Angular app using 'ng new poc-pwa-angular-v2', and then pushed it to a Bitbucket repositor ...

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...

In what time frame is Javascript/AJAX functioning?

Do you know if the times are measured in milliseconds or seconds? I'm puzzled why these two scripts aren't synchronizing - there's a significant delay. $(document).ready(function() { $("#idle").delay(300000).fadeIn(500); }); var interv ...

Drag to rotate using JavaScript when the mouse is pressed down

I am experimenting with making a spinning wheel rotate as the user drags the mouse over it. The wheel consists of 3 pieces, so I have individually mapped each image to target the specific section of the wheel that I want to rotate. Currently, it is funct ...