M
M
microf2015-10-07 13:34:10
Angular
microf, 2015-10-07 13:34:10

How to use ng-click in a directive with a controller?

All the same, directives kill me. We need to achieve understanding.
I do this on the page

<div ng-repeat="item in ctrl.products"> 
                          <add-to-cart item="item.name"></add-to-cart>  
  </div>

Directive
(function () {
    'use strict';
    angular
            .module('admin')
            .directive('addToCart', addToCart);
    function addToCart() {
        var directive = {
            link: link,
            scope: {
                'item': '=',
                'itemClick': '&'
            },
            transclude: true,
            template: '<div>{{item}}<button ng-click="addItem()">+</button></div>',
            restrict: 'EA',
            controller: AddToCartController
           
        };

        return directive;

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

        AddToCartController.$inject = [];

        function AddToCartController() {
            var vm = this;             
            vm.addItem = function (item) {
                alert(item);
           
            };
          
        }
    }
})();

Doesn't work vm.addItem
Tried to add to the page in the same way
<add-to-cart item="item.name" item-click="addItem(item)" ></add-to-cart>
- does not work.
If you add it to the link, it works.
$scope in the controller will have to be used?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2015-10-07
@microf

JSFiddle
https://github.com/johnpapa/angular-styleguide#sty...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question