简体   繁体   English

AngularJS - $ scope不绑定到DOM

[英]AngularJS - $scope does not bind to DOM

I'm very new to Angular and as practice, I'm building a small website. 我是Angular的新手,作为练习,我正在建立一个小网站。 On one of the pages, I want to be able to show the number of buttons have been clicked by data binding. 在其中一个页面上,我希望能够显示数据绑定所点击的按钮数量。 For it, I have this controller 对于它,我有这个控制器

'use strict';

angular.module('angularApp')
    .controller('MyCtrl', function ($scope) {
    var timer = 0;

    $scope.clicked = function () {
        timer++;
        console.log(timer);
        return timer;
    };

    $scope.actualTime = $scope.clicked(timer);
});

As for the view, I have: 至于观点,我有:

<button type="submit" ng-click="clicked()" class="btn btn-success">Start</button>
    <p>You clicked {{actualTime}} minutes ago.</p>

The controller is bound to the view via the $routeProvider. 控制器通过$ routeProvider绑定到视图。

Ideally, whenever I click on the button, {{actualTime}} value should be incremented. 理想情况下,每当我点击按钮时,{{actualTime}}值都应递增。 But it doesn't for some reason. 但它不是出于某种原因。 As far as I know, it should be binded (as in two-way data binding) so there shouldn't have to be a function that will update the DOM. 据我所知,它应该绑定(如在双向数据绑定中),因此不必是一个将更新DOM的函数。 The console.log updates with the correct increments, but the DOM doesn't. console.log以正确的增量更新,但是DOM没有更新。 Anyone wanna explain how this works? 有谁想解释这是如何工作的? I've read answers here and most, if not all of them, are too technical sounding. 我在这里读到了答案,大多数,如果不是全部,都是技术性的。 A dumbed down explanation would really help. 一个愚蠢的解释真的会有所帮助。 Thanks! 谢谢!

In you code you are not updating the variable 'actualTime' on every click. 在您的代码中,您不会在每次点击时更新变量“ actualTime”。

You can update the variable in two ways 您可以通过两种方式更新变量

1) You can update it for every click with in the called function 1)您可以在调用的函数中为每次单击更新它

http://plnkr.co/edit/o8Jq5jQn0DEg0mN2r7Zd http://plnkr.co/edit/o8Jq5jQn0DEg0mN2r7Zd

HTML HTML

<button type="submit" ng-click="clicked()" class="btn btn-success">
Click      
</button>
<p>You clicked {{actualTime}} minutes ago.</p>

JS JS

var timer=0;
$scope.actualTime = 0;
$scope.clicked = function () {
    timer++;
    $scope.actualTime = timer;
};

2) You can also update it using '$watch' also. 2)您也可以使用'$ watch'更新它。

HTML HTML

<p>Using $watch service  : You clicked {{actualTime2}} minutes ago.</p>

JS JS

If you have a varible '$scope.actualTime' defined, then when ever the variable '$scope.actualTime' changes, assign its new value to '$scope.actualTime2' 如果定义了变量'$ scope.actualTime',那么当变量'$ scope.actualTime'发生变化时,将其新值赋给'$ scope.actualTime2'

$scope.$watch('actualTime',function(newval, oldval){
  $scope.actualTime2 = newval;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM