最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS communication between controller and directive - Stack Overflow

programmeradmin3浏览0评论

How to get some data from controller and use it inside directive thats not a problem. But I stack with such situation when I need get data from directive and use it in my controller.

For exmpl:

My controller:

function MyController($scope, $location, myDirective) {
    "use strict";

    // here i need use scope.importantValue and create() method from directive

}

My directive:

        .directive("myDirective", function() {
"use strict";
return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    scope: {
        data: '=',
    },
    link: function(scope, elm) {
        scope.importantValue = "value";

        function create() {
            console.log("Directive works...");
        }

};
})

How I can use variables or/and methods from directive inside my controller?

How to get some data from controller and use it inside directive thats not a problem. But I stack with such situation when I need get data from directive and use it in my controller.

For exmpl:

My controller:

function MyController($scope, $location, myDirective) {
    "use strict";

    // here i need use scope.importantValue and create() method from directive

}

My directive:

        .directive("myDirective", function() {
"use strict";
return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    scope: {
        data: '=',
    },
    link: function(scope, elm) {
        scope.importantValue = "value";

        function create() {
            console.log("Directive works...");
        }

};
})

How I can use variables or/and methods from directive inside my controller?

Share Improve this question asked May 10, 2013 at 13:23 LugaruLugaru 1,4603 gold badges25 silver badges39 bronze badges 3
  • 1 Why would you want to do that? – lucuma Commented May 10, 2013 at 13:38
  • 2 you are not suppose to do it – Arun P Johny Commented May 10, 2013 at 13:56
  • We moved to directive some part of code that similar for few views and this directive contains some variables that can be used in other parts of project. I wanna know is it posible to use this variables in a controller or not? – Lugaru Commented May 10, 2013 at 14:03
Add a ment  | 

1 Answer 1

Reset to default 9

The simplest way to acplish this is to make both your controller and directive get importantValue and create() from a service.

angular.module(/* Your module */).service('sharedData', function () {
    return {
        importantValue: "value",
        create: function () {
            console.log("Directive works...");
        }
    };
});

Now you can inject sharedData into your directive and controller and access importantValue and create() from either place.

发布评论

评论列表(0)

  1. 暂无评论