Leveraging Directive Class Scope Variable in Controller Class with Angular and Typescript

Struggling with Angular Typescript once again, this time dealing with directives and controllers. I am attempting to pass an object from a page to a directive and then utilize that object in the controller of the directive. While it may not be the most efficient approach, it seems logical to me; however, I'm having difficulty accessing the object in the controller.

HTML snippet from the page:

<div>
    <section>
        On View: {{ee.obj.name}}
        <image-upload obj="ee.obj"></image-upload>
    </section>
</div>

Directive template section:

<div>
    On directive: {{obj.name}}
    On controller: {{iuc.obj.name}}
    <div class="row">
        <div class="col-md-4 text-primary h4">
            Add Images
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
            <input type="file" multiple ng-model="iuc.imageUploads" ng-change="iuc.uploadImages()" />
        </div>
    </div>
    <div class="row">
        <div class="col-md-3 dropzone"></div>
    </div>
</div>

Typescript code for the directive:

/// <reference path="../../../scripts/_all.ts" />

module ObjConfig {
    'use strict'

    export class ImageUpload implements ng.IDirective {
        static instance(): ng.IDirective {
            return new ImageUpload();
        }
        restrict = 'E';
        replace = true;
        templateUrl = '../../../../App/AppConfig/Views/Directives/ImageUpload.html';
        scope = {
            obj: '='
        };
        controller = imageUploadCtrl;
        controllerAs = 'iuc';
    }

    export class imageUploadCtrl {
        obj: OBJBase;
        imageUploads: OBJImage[];

        constructor() {
        }

        uploadImages() {
            //THIS IS WHERE I WANT TO ACCESS OBJ 
            //this.imageUploads.forEach((iu) => { this.obj.images.push(iu); });
        }
    }

    angular.module('ObjConfig').directive('imageUpload', ImageUpload.instance);
}

Although "this.obj" in the method returns undefined, indicating that the controller's "obj" is not automatically linked to the directive's "obj", the value of ee.obj.name on the page is displayed, as well as the obj.name at the top of the directive template. However, the iuc.obj.name does not display any value. I have attempted to connect the directive's obj to the controller's obj using a link function with ng.IAttributes, but all it provides is ee.obj without giving me the actual object.

I would greatly appreciate any assistance with this issue.

Answer №1

If you want to achieve your goal, consider using the bindToController: true option.

This functionality is outlined in the $compile documentation, making it a bit challenging to find, but it serves the purpose you're aiming for.

By utilizing an isolate scope with a component (as mentioned above) and using controllerAs, setting bindToController: true allows a component's properties to be linked to the controller instead of the scope. This means that when the controller is initialized, the initial values of the isolate scope bindings are already accessible.

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

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...

Pairing up with JavaScript

Currently in the process of developing a web interface for XBMC that involves ajax. Because of the limitations of our ajax functionality, I had to resort to using local resources instead of my usual ajax class which generates output. I am working with a sp ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

How to refresh a label in a GridView?

I have created a wall with nested comments where users can comment on posts. The issue I'm facing is that whenever someone clicks on the thumbs up button, the entire page reloads. What I want is for only the label displaying the number of likes to be ...

Adjusting ng-required in AngularJS for both empty values and -1

When an empty value or -1 is selected in my form, it should display an error message saying "This field is required". I have explored two possible solutions: 1. Using ng-required with regular expression. 2. Writing ctrl.$validators.required in the dir ...

Troubleshooting Problem with MVC Ajax Requests

When working with an MVC view, I have a submit button that includes validation checks. If the validation fails, I return false to prevent the form from being submitted. In addition to standard validation, I also use an Ajax GET request to check for duplic ...

Repeatedly utilizing a drop-down menu

Can a <select> menu be written and utilized in multiple locations on a webpage? For instance: <select id="dm"> <option value="">Select Quantity</option> <option value="less ">50 - 60</option> <option value="me ...

Problem with sending data using $.ajax

I stumbled upon a strange issue. In one of my php pages, I have the following simple code snippet: echo $_POST["donaldduck"]; Additionally, there is a script included which makes a $.ajax call to this php page. $.ajax({ url: "http://provawhis ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

How can I detect a click event on an SVG element using JavaScript or jQuery?

Currently, I am developing a web application that utilizes SVG. However, I have encountered an issue: I am struggling to add a click event to each element within the SVG using jQuery. The problem arises when attempting to trigger the event; it seems like t ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Implementing conditional dropdown menus with CodeIgniter

Explore the District Master Table: https://i.sstatic.net/n6kvV.jpg Dive into the District table: https://i.sstatic.net/uQqcW.jpg District Master District I need assistance with a form page that includes a Category dropdown. The district table stores d ...

Building a webRTC peer using only a JavaScript interpreter, no browser required

My goal is to develop a WebRTC peer that functions solely as a listener/recorder without any graphical presentation like HTML/CSS involved. If achievable using the WebRTC JavaScript APIs, I am curious about which standalone JavaScript engine I should cons ...

Host app is failing to render shared components in SSR

Encountering an issue while implementing SSR with module federation? Check out my code example Steps to Begin: Run yarn install:all command Execute yarn shell:server:build task Start the server using yarn shell:server:start Initiate remote services with y ...

Creating a Toggle Function for the Hamburger Menu in JavaScript

Struggling to create a responsive navbar with a hamburger menu toggle. Followed an online tutorial and managed to get everything working, except for the toggle functionality of the menu. Clicking on the icon does nothing. Being new to this, I'm not su ...

NodeJs simple mock: Capturing query string parameters with ease

I'm currently developing a basic mock server using only JavaScript and Yarn. Simply put, I have this functional code snippet: function server() { (...) return { users: generate(userGenerator, 150) } This piece of code successfully generates 15 ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...

when webpack loads the bundle.js file, the mime type is converted to text/html

I'm currently working on implementing server side rendering for an application using react-redux and express for the server. We are also utilizing webpack to bundle our assets. To get started, I referred to the following documentation: https://redux ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...