当单击一个按钮时,我如何在AngularJs中设置一个指令的值

时间:2013-03-28 02:58:02

标签: javascript angularjs angularjs-directive

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

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

      });
    }
  };
});

1 个答案:

答案 0 :(得分: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