#StackBounty: #angularjs #angularjs-directive #angular-ui-router #angularjs-scope How to get data from a page with a parent route contr…

Bounty: 50

I’m using Angularjs 1.4x and I have a page that has a controller declared something like this:

$stateProvider
        .state('myPage', {
            url: '/my-page',
            templateUrl: templateUrl,
            controller: 'searchCtrl', ...

On that page I have a directive, called myDirective that has a button with ng-click that sends some text as a parameter back to the directive controller. What I’m trying to do is get that parameter value back to the directive when the user clicks the button and then call another controller to get that parameter value and open a modal.

If I use $scope I can get the value from searchCtrl, but I’ve been unable to figure out a way to get the directive to receive the parameter value. In the past, I would put the button in the template, but here the button is already in the myPage.html page.

I know now that that I can’t use ng-controller on the page as it already has a controller from the $route, which is searchCtrl. So what is the proper way to do this?

Here is my code, but I don’t have ui-router in it, but I don’t know if that matters, and the plunker:

Index.html

<!DOCTYPE html>
<html>
  <head>
    https://code.angularjs.org/1.4.2/angular.js
    <link rel="stylesheet" href="style.css" />
    http://script.js
  </head>

  <body>
    
</div> </body> </html>

myPage.html

script.js

// Code goes here
var app = angular.module('app', []);
app.controller('myCtrl', function($scope){

  $scope.ctrlFn = function(param) {
      console.log("param is: " + JSON.stringify(param));
  };  
});

function newCtrl($scope) {
  //How can I call this function from inside the directive and pass in param?
  //Do something here
}

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      ctrlFn: '&'
    },
   templateUrl: "./myPage.html",
    link: function(scope, element, attributes, controller) {
      scope.ctrlFn = scope.ctrlFn();

    }
  };
});

Any ideas on how to implement this properly?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.