Angular:如何在2个独立的div之间共享(控制器)$ scope?

时间:2021-02-16 12:09:56

I have the following HTML:

我有以下HTML:

<div>
  <h1>My App</h1>
  <div id="search" ng-controller="TagsController">
    <input type="text" ng-model="tags_to_search" />
    <button ng-click="search(tags_to_search)" />
  </div>
</div>
<div>
  <div id="results" ng-controller="TagsController">
    going to search {{tags_to_search}}
    <ul>
      <li ng-repeat="tag in searched_tags">
        {{tag.name}} - {{tag.counter}}
      </li>
    </ul>
  </div>
  <div ng-controller="DataController">

  </div>
</div>

The TagsController $scope includes a searched_tags which is populated when the button is clicked, so the #search div is supposed to update the #results div (when the button is clicked, and when the textbox is populated).

TagsController $ scope包含一个在单击按钮时填充的searching_tags,因此#search div应该更新#results div(单击按钮时,以及填充文本框时)。

In fact, nothing happens and they both look unrelated although I set the same controller for both #search and #results. I can have a wrapper div that will take the TagsController instead of the #search and #results div, but my UI is built in a way that such a wrapper will cause the DataController to be nested in the Tags controller although it's totally wrong logically and they have nothing to do together.

实际上,没有任何反应,虽然我为#search和#results设置了相同的控制器,但它们看起来都不相关。我可以有一个包装器div,它将使用TagsController而不是#search和#results div,但是我的UI构建方式使得这样的包装器会导致DataController嵌套在Tags控制器中,尽管它在逻辑上是完全错误的他们无所事事。

Any suggestions how I can go through this?

有什么建议我可以通过这个吗?

2 个解决方案

#1


Would this not work?

这不行吗?

<div ng-controller="TagsController">
    <h1>My App</h1>
    <div id="search">

#2


Since Data controller has nothing to do with Tags controller and you don't want it nested, can you go with this?

由于数据控制器与标签控制器无关,你不希望它嵌套,你可以使用它吗?

<div ng-controller="TagsController">
  <h1>My App</h1>
  <div id="search" >
    <input type="text" ng-model="tags_to_search" />
    <button ng-click="search(tags_to_search)" />
  </div>
  <div id="results" >
    going to search {{tags_to_search}}
    <ul>
      <li ng-repeat="tag in searched_tags">
        {{tag.name}} - {{tag.counter}}
      </li>
    </ul>
  </div>
</div>
<div ng-controller="DataController">

</div>

#1


Would this not work?

这不行吗?

<div ng-controller="TagsController">
    <h1>My App</h1>
    <div id="search">

#2


Since Data controller has nothing to do with Tags controller and you don't want it nested, can you go with this?

由于数据控制器与标签控制器无关,你不希望它嵌套,你可以使用它吗?

<div ng-controller="TagsController">
  <h1>My App</h1>
  <div id="search" >
    <input type="text" ng-model="tags_to_search" />
    <button ng-click="search(tags_to_search)" />
  </div>
  <div id="results" >
    going to search {{tags_to_search}}
    <ul>
      <li ng-repeat="tag in searched_tags">
        {{tag.name}} - {{tag.counter}}
      </li>
    </ul>
  </div>
</div>
<div ng-controller="DataController">

</div>