0

我的代码中有一些注释。但这是它的基础知识。我有一个跨度,我有一个按钮。单击按钮时,我想更新跨度的 html。跨度绑定到控制器属性的值。我尝试使用模型,但它也不起作用。这是我的代码

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() { 

      });
    }
  };
});
4

1 回答 1

3

我认为您根本不需要指令,这可以简单得多。

将这些直接放在您的视图中:

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

然后在你的控制器中:

  $scope.count = 0;

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

工作示例:http: //jsbin.com/ehohud/1/edit

于 2013-03-28T03:02:29.687 回答