简体   繁体   English

Angular Directives 2向绑定和刷新

[英]Angular Directives 2 way binding & refresh

Let's say you have a page where you have a directive for customer search (1st directive). 假设您有一个页面,其中有一个用于客户搜索的指令(第一指令)。 You do a search and you get back a list of customers from a web server. 您进行搜索,然后从Web服务器获取客户列表。

Now, inside the directive above, you have a 2nd directive, let's call it customerRes , that displays some info for the customers (this is like a small widget reused in many places in your site). 现在,在上面的指令中,您有了第二个指令,我们将其称为customerRes ,它为customerRes显示一些信息(这就像在站点中许多地方重复使用的小窗口小部件一样)。 Inside the isolated scope of this 2nd directive I have an attribute called results that I bound from the results returned eg 在第二个指令的隔离范围内,我有一个称为results的属性,我将它与返回的结果绑定在一起,例如

The 1st directive has a declaration like 第一个指令的声明如

<customer-res results="webserverResult">

and inside the customerRes directive I have something like a customerRes指令中,我有一个类似

<div ng-repeat="x in results>
{{name}} {{bla}}  ... bla bla
</div>

Now everytime the user clicks the parent directive, it will make a request to the web server and perhaps get different results back. 现在,每次用户单击父指令时,它将向Web服务器发出请求,并可能返回不同的结果。

The question: Does angular actually monitor itself that the value bound to the isolated scope changed outside the directive, or do I need to do something to make sure that it invalidates? 问题:角度实际上是在监视自身,即与隔离范围绑定的值在指令之外发生了变化,还是我需要做一些事情以确保其无效?

Also, even if you load your page before the results get back, once they get back shouldn't they update the page elements? 此外,即使您在结果返回之前加载页面,但一旦返回结果,它们是否不应该更新页面元素?

A cool way is you will find out for yourself. 一种很酷的方法是您自己找到自己的地方。 Don't get me wrong, but personally I did this when walking my first steps in angular. 别误会我的意思,但是我个人在迈出第一步时就做到了。 Helps to understand the framework more deeply rather reading the docs and forget more easily. 帮助您更深入地了解框架,而不是阅读文档并更容易忘记。

You can always add 您可以随时添加

scope.$watch('myVariable', function(value) { 
  console.log('myVariable changed to:', value);
})

to your directives and see when its value changes. 转到您的指令,并查看其值何时更改。

Two-way-bindig works like a charm, even on full page reloads. 即使在整页重新加载时,双向bindig也像超级按钮一样工作。 Cannot be more precise without your directive's JS code. 没有指令的JS代码,就无法更精确。 But when using isolated scopes, probably directives need 但是,当使用隔离范围时,可能需要使用指令

scope: {
   myVariable: '='
}
<my-directive my-variable="results.entries"></my-directive>

But keep in mind, that when reloading the page, angular restarts from zero. 但请记住,重新加载页面时,角度从零重新开始。 Meaning for each directive its link function is called once and many many other things under the hood. 对于每个指令而言,其链接功能在幕后都会被调用一次。 Keyword is angular's digest cycle . 关键字是angular的digest cycle

Hope I could help with this (a bit more broad) answer. 希望我可以帮助您(稍微广泛一点)。

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

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