如何在Angular JS控制器的范围变量中更新Vanilla JS变量

时间:2017-01-24 07:44:04

标签: javascript angularjs

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但是无法使它工作。

1 个答案:

答案 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 servicefactory

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;
        }
    };
});