gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:34:39 24 4
gpt4 key购买 nike

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

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

});
}
};
});

最佳答案

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

将这些直接放在您的 View 中:

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

然后在你的 Controller 中:

  $scope.count = 0;

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

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

关于javascript - 单击按钮时,如何在 AngularJs 中设置一个指令的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15673475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com