简体   繁体   English

对AngularJS中的数据绑定的怀疑

[英]Doubts about data binding in AngularJS

I'm learning AngularJS by doing my first app with it. 我正在通过第一个应用程序学习AngularJS。 As far as now, everything was working ok and I'm pretty excited :) 到目前为止,一切正常,我很兴奋:)

But now I have a console.log that is totally confusing me, and I'm start thinking I've completely missed something. 但是现在我有了一个console.log,这完全使我感到困惑,并且我开始认为我已经完全错过了一些东西。

I have a simple tag bound to a controller: 我有一个绑定到控制器的简单标签:

<h2 ng-controller='HeaderController' ng-show='data.actualSection > 0'>
    {{titleForSection()}}
</h2>

The controller is very simple: 控制器非常简单:

    uxctModule.controller ('HeaderController', function ($scope, ModelData){
    $scope.data = ModelData;

    $scope.titleForSection = function () {
        console.log ("RETURNING IT");
        return ("I SHOULD RETURN YOU SOMETHING");
    }
});

What's really confusing me is that I've noticed that every time something is changing in the model, the function is triggered. 真正让我感到困惑的是,我注意到每次模型中的某些变化时,都会触发该函数。 How can the controller be executing the function constantly without a $watch in it? 没有$ watch的情况下,控制器如何连续执行该功能?

Data binding in angular is done via a digest loop, which means that angular loops over and over again checking for changes, and in the case of a function that is bound to the function must be evaluated looking for changes. 角度数据绑定是通过摘要循环完成的,这意味着角度循环反复检查更改,对于绑定到该功能的功能,必须进行评估以寻找更改。

This is the reason it is generally a bad idea to bind your UI to the result of a function. 这就是将UI绑定到函数结果通常是个坏主意的原因。 Instead you should do something like this: 相反,您应该执行以下操作:

Markup: 标记:

<h2 ng-controller='HeaderController' ng-show='data.actualSection > 0'>
    {{sectionTitle}}
</h2>

Controller: 控制器:

$scope.sectionTitle = 'I SHOULD RETURN YOU SOMETHING';
//and update it dynamically
$scope.funcToUpdateTitle = function(newTitle){
    $scope.sectionTitle = newTitle;
};

Actually in angularJS all functions related to view will be called as and when a digest cycle is called in that way since you have called titleForSection() in your HTML so when where an event occurs in the HTML, causes the function to be executed. 实际上,在angularJS中,与View相关的所有函数都将被调用,并且当以这种方式调用摘要循环时,因为您已经在HTML中调用了titleForSection() ,所以当HTML中发生事件时,该函数将被执行。

Hope it helps! 希望能帮助到你!

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

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