J
J
JIakki2015-02-23 11:39:26
JavaScript
JIakki, 2015-02-23 11:39:26

How to get the controller's this from a directive?

app.directive("name", function () {
   controller : function () {
   
   },
   link:function(scope,elem,attr,contr){
        // от сюда
       // взять this котроллера . например selfContr
       selfContr.method = fucntion () {
           return elem 
     }
   }
}
app.directive("name2", function () {
   require : "name", 
   controller : function () {
      //this
   },
   link:function(scope,elem,attr,contr){
      contr.method();
   }
}

How can I get the "this" of the controller from the name directive so that I can pass another directive to the controller later?
Is using $emit a better option?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
Boris Benkovsky, 2015-02-23
@benbor

See how useful it is to read off-line documentation
https://docs.angularjs.org/guide/directive#creatin...
Directly your code!

M
Mikhail Osher, 2015-02-23
@miraage

DEMO

// Code goes here

angular.module('app', [])
.controller('FooCtrl', FooController)
.controller('BarCtrl', BarController)
.directive('foo', fooDirective)
.directive('bar', barDirective);

FooController.$inject = ['$window'];
function FooController($window) {
  this.notify = function() {
    $window.alert('foo ctrl');
  };
}

FooController.$inject = ['$window'];
function BarController($window) {
  this.notify = function() {
    $window.alert('bar ctrl');
  };
}

function fooDirective() {
  return {
    controller: 'FooCtrl'
  };
}

function barDirective() {
  return {
    controller: 'BarCtrl',
    controllerAs: 'ctrl',
    require: 'foo',
    link: function(scope, elem, attrs, ctrl) {
      if (elem[0].tagName === 'A') {
        elem.on('click', function() {
          ctrl.notify();
        });
      } else {
        elem.on('click', function() {
          scope.ctrl.notify();
        });
      }
    }
  };
}

J
JIakki, 2015-02-23
@JIakki

this is how you can

app.directive("name", function () {
   controller : function ($scope) {
      var self = this;
      $scope.toThis = function (name , data ) {
          self[name] = data
      }
   },
   link:function(scope,elem,attr,contr){
      scope.toThis("slide", elem)
   }
}
app.directive("name2", function () {
   require : "name", 
   controller : function () {
      //this
   },
   link:function(scope,elem,attr,contr){
      contr.slide
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question