如何在AngularJS中实现JavaScript闭包?

时间:2017-12-12 05:28:11

标签: javascript angularjs closures

我正在使用一个函数来计算按钮的点击次数,如下所示:

$scope.counterFunc = (function(){
    var count = 0;
    console.log('i will be consoled only once');
    return function(){
        console.log(count);
        return ++count;
    }
})();

查看:

<button ng-click="counterFunc()">click me</button>
<div>  
    {{ count value }}
</div>

我能够控制count value,但如何在视图中显示它。

我可以使用$scope变量绑定count value来查看,但我担心的是count counterFunc() >

还有其他办法吗?..

2 个答案:

答案 0 :(得分:1)

counterFunc()每次ng-click执行时,<button ng-click="count = counterFunc()">click me</button> <div> {{ count }} </div> 已经返回递增的值。您可以将其分配给视图中的变量,如此

count

请注意$scope属性将由count中的上述解决方案创建,但与counterFunc()内的$scope.count变量不同,并且会更改var count不会影响button。您可以通过添加其他$scope.count来重置<button ng-click="count = counterFunc()">click me</button> <div> {{ count }} </div> <button ng-click="count = 0">Reset</button>

的值来对此进行测试
button

现在,您会看到每次按下重置0时,显示的值将变为click me。但是,当您再次按var count时,它将从上一个值 Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\login_oracle\funcs\funcs.php:120 Stack trace: #0 C:\xampp\htdocs\login_oracle\registro.php(61): registraUsuario('wae', '$2y$10$kmC83r2H...', 'wqe', 'wad@awd.cl', 0, '33fc8f862db7095...', 2) #1 {main} thrown in C:\xampp\htdocs\login_oracle\funcs\funcs.php on line 120 开始。

答案 1 :(得分:-2)

<script>
        var app=angular.module('countButton',[]);
        app.controller('countController',function($scope){
            $scope.count = 1;
            $scope.countClick = function () {
                $scope.count++;
            }
        });
    </script>
    <div ng-app="countButton" ng-controller="countController">
        <input type="button" ng-model="count" ng-click="countClick()">
        <label> No of clicks </label>{{count}}
    </div>

试试这个。