0

I have some comments in my code. But here is the basics of it. I have a span and I have a button. When the button is clicked I want to update the html of the span. The span is bound to the value of a controllers property. I tried using a model but it was not working either. Here is my code

app.controller('CartController', function($scope) {
  this.count = 0;

  this.getCount = function() {
    return count;
  };
  this.addProduct = function() {
    this.count = this.count + 1;
    return this.count;
  };
});

//this is a span with a value set to the number of items in the cart
app.directive('cartCount', function() {
  return {
    restrict: 'A',
    controller: 'CartController',
    template: '<span>{{count}}</span>',
    transclude: true,
    link: function(scope, element, attrs, CartController) {

      //I can initially set the value 
      scope.count = CartController.count;

      //but later how do I watch the value of the CartControllers count property and sync it with the value of this?
    }
  };
});

//this is a button
app.directive('addProduct', function() {
  return {
    restrict: 'C',
    controller: 'CartController',
    link: function(scope, element, attrs, CartController) {

      //when button is clicked I want the cartCount directives value to be updated 
      element.click(function() { 

      });
    }
  };
});
Subtubes
  • 15,851
  • 22
  • 70
  • 105

1 Answers1

3

I don't think you need directives here at all, this can be a lot simpler.

Put these directly in your view:

<span>{{count}}</span>
<a href="#" ng-click="addProduct()">Add Product</a>

Then in your controller:

  $scope.count = 0;

  $scope.addProduct = function() {
    $scope.count++;
  };

Working example: http://jsbin.com/ehohud/1/edit

jszobody
  • 28,495
  • 6
  • 61
  • 72
  • Dude that totally did it. I am so used to not putting any JavaScript in my markup that I try to fix everything with directives – Subtubes Mar 28 '13 at 03:07
  • 2
    Actually it's better to use ng-bind on a span, then to use the braces approach. This to prevent a FOCB ("flash of curly brackets") upon first page load. See also: http://stackoverflow.com/questions/16125872/why-ng-bind-is-better-than-in-angular – jngrt Apr 01 '14 at 12:46