【问题标题】:AngularJS: Input form does not work inside the partialAngularJS:输入表单在部分内部不起作用
【发布时间】:2015-02-21 22:55:48
【问题描述】:

页面的层次结构如下:

<div ng-include="'partials/navbar.html'"></div>
<div ng-view></div>
<div ng-include="'partials/footer.html'" id="footer"></div>

这是主要的 index.html,其中还包含所有脚本源。

在 ng-view 中还有另一个使用部分标头的索引:

div ng-include="'partials/header_search.html'"></div>

此 header_seatch 部分包含基于角度的输入表单

<form name="searchLocation" ng-submit="search()">
        <div class="input-group">
        <input type="text" name="location" ng-model="location" ng-autocomplete ng-change="error = false"/>

        <div class="input-group-addon">
            <button type="submit">Search</button>
        </div>
        </div>
        <span ng-if="error">No such address</span>
    </form>

我遇到的问题来了——下面的表单放在部分标题中时没有响应。当我将它复制/粘贴到索引视图中时,一切正常。角度是否与放置在部分中的 ng-stuff 有任何混淆?我应该修改什么以使其在标题部分中工作?

提前致谢!

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    ng-include 有它自己的范围,这非常令人困惑。我建议用指令替换 ng-include。

    否则这应该有效:

    <form name="searchLocation" ng-submit="$parent.search()">
     <div class="input-group">
     <input type="text" name="location" ng-model="$parent.location" ng-autocomplete   ng-change="error = false"/>
        <div class="input-group-addon">
            <button type="submit">Search</button>
        </div>
        </div>
        <span ng-if="$parent.error">No such address</span>
    </form>
    

    请注意,使用 $parent 是不好的做法,应该避免。

    【讨论】:

    • 现在可以了!非常感谢。不过我必须承认,ng-include 指的是不同的范围,这非常令人困惑!
    • 是的,这就是我更喜欢使用指令的原因。如果可以的话,我会切换到指令。
    • 这可能是更健壮的解决方案,但目前您提供的代码完全符合我的要求。
    • 太棒了! :-) 在这种情况下,请接受答案,以便其他人可以找到它。
    • 使用 $parent 通常是不好的风格。 IE。使用 $parent.search() 是无稽之谈,除非你在不同的范围内有两个同名“搜索”的函数。否则只需使用简单的 search() - 它会在父范围内找到函数。 $parent.error 也是如此 - 你可以在读取变量时只使用错误。唯一不起作用的 - 从子范围更改父范围变量。 (这里是 $parent.location)所以你有时可能会为此使用 $parent。但是在这里您的父范围根本不需要位置。所以 ng-model="location" 和 search(location) 就是你所需要的。
    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多