簡體   English   中英

如何在Angular JS控制器的作用域變量中更新Vanilla JS變量

[英]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 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;
        }
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM