@JIakki

Как получить this контроллера из директивы?

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();
   }
}


Как я могу получить "this" котроллера из директивы name, чтобы передать потом в контроллер другой директивы?
Лучший ли вариант с помощью $emit ?
  • Вопрос задан
  • 2302 просмотра
Пригласить эксперта
Ответы на вопрос 3
benbor
@benbor
Помог ответ - не забудь лайкнуть
Смотрите, как полезно читать офф документацию
https://docs.angularjs.org/guide/directive#creatin...
Прямо Ваш код!
Ответ написан
miraage
@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();
        });
      }
    }
  };
}
Ответ написан
@JIakki Автор вопроса
вот так можно
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
   }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы