![](/img/trans.png)
[英]Angular JS how to update scope variable inside another scope variable
[英]How to update Vanilla JS variable in scope variable of Angular JS controller
var a=1;
function counterincrease(){
a++;
}
angular.module('myapp')
.controller('MainCtrl',function($scope){
$scope.b = a;
});
我想在$scope.b
繼續跟蹤變量a
<button onclick="counterincrease()">Click me</button>
如何保持追蹤? 我試圖將手表戴在上a
但無法正常工作。
使用ng-click
<button ng-click="counterincrease()">Click me</button>
在$scope
創建一個counterincrease
函數,然后從中調用全局方法並在ngClick
處理程序中更新b
。
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;
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.