0
我在代碼中有一些註釋。但這是它的基礎。我有一個跨度,我有一個按鈕。當按鈕被點擊時,我想更新span的html。跨度綁定到控制器屬性的值。我嘗試過使用模型,但它也沒有工作。這裏是我的代碼如何在AngularJs中單擊某個按鈕時設置一個指令的值
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() {
});
}
};
});
多德說完全做到了。我習慣於不把任何JavaScript放在我的標記中,我試圖用指令修復所有的東西 – 2013-03-28 03:07:35
實際上,最好在跨度上使用ng-bind,然後使用大括號方法。 這樣可以防止第一次加載頁面時發生FOCB(「大括號閃爍」)。另見:http://stackoverflow.com/questions/16125872/why-ng-bind-is-better-than-in-angular – jngrt 2014-04-01 12:46:34