Using Angular 1.x directive with a shared scope and a parent controllerAs approach

I'm currently working on a directive that needs to call a specific method declared within the parent controller.

Feel free to check out my Plunker example here

Within the parent controller, I am utilizing the 'controller as vm' syntax. However, I'm encountering an issue where the method is not being triggered from the directive. How can I successfully invoke a method from the parent controller in the directive?

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

  myApp.controller('MyCtrl', MyCtrl);

  MyCtrl.$inject = [];

  function MyCtrl() {
    this.title = 'Test';

    this.sayHello = () => {
      this.output = 'Hello';
    }

  }

  myApp.directive('sayHello', function() {
    return {
      restrict: 'E',
      replace: true,
      template: '<a href="#" ng-click="vm.sayHello();">Click to say hello</a>'
    }
  })
})();

Answer №1

I just revised the code and now it's functioning properly:

<!DOCTYPE html>
 <html>
  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b3bcb5a7beb3a0fcb8a192e3fce6fceb">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="myApp">
      <div ng-controller="MyCtrl as vm">
      <h3>{{vm.title}}</h3>
      <say-hello></say-hello>

      <h4>{{vm.output}}</h4>
      </div>
    </div>
  </body>

</html>

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

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

There is a discrepancy with the rectangular data object when trying to add a response interceptor, as it is undefined

After using Restangular, I encountered an issue where the get method/promise resolves, but the result passed to .then() is empty. A console.log(data) statement results in 'undefined'. Strangely, when checking the network tab in Chromium debug, th ...

Troubleshooting AngularJS Get Function Failure

New to the world of AngularJS, I find myself faced with a challenge. My .NET MVC WebAPI Restful app is up and running on an IIS server. However, when I attempt to query the API using , the response I receive is: [{"Id":1,"Name":"Glenn Block","Created":"00 ...

Tips on retrieving an object in a JavaScript function through an HTML event

The js function code is as follows: //Assigning the index of theater array to a variable $scope.setTheaterValue = function(name) { var index = $scope.path.map(function(s){return s.name}).indexOf(name); $scope.path = $scope.path[index]. ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

Using AngularJS to update attributes in an HTML tag within a string

My string contains HTML tags : var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src='urlAAA' height='400' width=&ap ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Storing multiple entries in a single MySQL cell along with JSON data

I have numerous folders named after different series on my website. Each series folder contains its own chapters, with each chapter containing images. As my website is a manga (comic) site, I want to store the paths of these folders and images in MySQL and ...

What is the best way to link multiple checkboxes to a single ng-model?

Currently, I am working on mobile app development using the Ionic framework. In order to set multiple checkboxes with the same ng-model, I want all three checkboxes to be clicked when one is selected. However, the values are not being stored as expected. ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

Using `ngIf` to loop through two distinct arrays

Looking at this code snippet: <tr ng-repeat="row in someController.searchResults" ng-class="{'selected': tableRow.selected}" ng-click="selectRow(tableRow)" > This piece of code is iterating through the searchResults array. I&ap ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...

Anticipating outcome: row 1 column 1 (character 0) in Python

As a newcomer to the world of Python, I am currently attempting to parse data in my application using the following lines of code: json_str = request.body.decode('utf-8') py_str = json.loads(json_str) Unfortunately, when I reach this line (jso ...

Issue with Ng-Messages not functioning properly due to a custom ng-Include directive lacking a child scope

I have created a custom directive called lobInclude, which is similar to ngInclude but with no isolated scope: .directive("lobInclude", ["$templateRequest", "$compile", function($templateRequest, $compile) { return { restrict: "A", ...

"Empty $stateParams Issue Encountered in Angular UI-Router While Using My Directive

I have developed a unique directive in my angular application for a custom navbar. The controller of this directive utilizes $stateParams to access a variable named lang, as shown below: .config(function($stateProvider, $urlRouterProvider, LANG) { $u ...

Prevent multiple instances of Home screen app on iOS with PWA

There seems to be an issue with the PWA app not functioning properly on iOS devices. Unlike Android, where adding an app to your homescreen will prompt a message saying it's already installed, iOS allows users to add the app multiple times which is no ...

Check out this Angular demonstration page!

Looking to demonstrate the features of my Angular page using a plugin like intro.js, however, only part of the page is shown upon loading. Users are greeted with an input box to fill out an id and submit before the rest of the page is displayed after makin ...

Renewing individual parental resolution cache

Is there a way to update specific resolves in the parent resolves without refreshing the entire page? Can resolve caching be disabled for certain items in ui-router? In my current setup, the company object is passed to 2 child states by an abstract parent ...