M
M
microf2015-10-07 09:05:38
Angular
microf, 2015-10-07 09:05:38

How to work with controller in directive?

Something I'm stupid in the morning.
I make a directive that should produce a list received from the service

(function () {
    'use strict';
    angular
            .module('admin')
            .directive('addToCart', addToCart);
    function addToCart() {
        var directive = {
            link: link,
            template: '<div ng-repeat="item in items">{{item.name}}</div>',
            restrict: 'EA',
            controller: AddToCartController,
            conrollerAs: 'addto'
        };

        return directive;

        function link(scope, element, attrs,ctrl) {
             
        }

        AddToCartController.$inject = ['Product'];

        function AddToCartController(Product) {
            var vm = this;
            vm.items = Product.query();
                   }
    }
})();

But I got it vm.items
. I need to connect it somehow in a link or what? I'm sorry for such a question, well, I'm really dumb.
Update Well, yes. Probably should be sent $scope.items = vm.items;to the link

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-10-07
Protko @Fesor

you don't need a link here. The only thing you need here is to specify an isolated scope so that there are no conflicts with other directives.

return {
            template: '<div ng-repeat="item in items">{{item.name}}</div>',
            restrict: 'EA',
            controller: AddToCartController,
            conrollerAs: 'addto',
            scope: {}
        };

link is needed only if you need directives to work correctly
- there is a need to work with the DOM, for example, hang events or something else
- there is a need to monitor data changes in attributes (attr.$observe and scope.$watch only in link), to pull the controller method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question