var a=1;
function counterincrease(){
a++;
}
angular.module('myapp')
.controller('MainCtrl',function($scope){
$scope.b = a;
});
我希望在a
$scope.b
<button onclick="counterincrease()">Click me</button>
如何跟踪它?我试着把手表放在a
但是无法使它工作。
答案 0 :(得分:0)
使用ng-click
<button ng-click="counterincrease()">Click me</button>
在counterincrease
中创建$scope
函数,然后从中调用全局方法并更新b
处理程序中的ngClick
。
angular.module('myapp')
.controller('MainCtrl', function ($scope) {
$scope.b = a;
$scope.counterincrease = function(){
counterincrease();
$scope.b = a;
};
});
无需在全局范围中定义该功能。我建议您使用Angular service
或factory
var app = angular.module('myapp');
app.controller('MainCtrl', ['$scope', 'myFactory', function ($scope, myFactory) {
$scope.b = myFactory.getData();
$scope.counterincrease = function () {
myFactory.counterincrease();
$scope.b = myFactory.getData();
};
}]);
app.factory('myFactory', function ($http) {
var a = 0;
return {
counterincrease: function () {
return a++;
},
getData: function () {
return a;
}
};
});