【问题标题】:AngularJS - ng-include ng-controller and scope not bindingAngularJS - ng-include ng-controller 和范围不绑定
【发布时间】:2014-02-17 23:31:57
【问题描述】:

我有以下主视图

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

options.html 有以下内容

<div ng-controller="OptionsController">Options</div>
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>

但是“关键字”没有绑定到 OptionsController 中的范围。

app.controller('OptionsController', 
              ['$scope', function($scope) {

  $scope.keyword = "all";
  $scope.search = function() {
    console.log("hello")
  };

}]);

当我点击按钮时,我没有看到 hello 并且关键字 all 没有出现在输入文本中。

我尝试如下移动 ng-controller 部分

<div ng-controller="OptionsController" ng-include="'otions.html'"></div>

一切都按预期进行。

我阅读了AngularJS - losing scope when using ng-include 中的答案 - 我认为我的问题是相关的,但只需要更多解释来了解发生了什么。

【问题讨论】:

  • 不确定这里是否是错字,但您的来源中也有:您所包含的文件引用为otions.html 而不是options.html
  • 在您的源代码中,您仅为第一个 div 指定 ng-controller,因此您的输入和按钮不在控制器的范围内。可能这是一个错字。如果不是,那可能是一个原因。

标签: javascript angularjs


【解决方案1】:

你应该像这样编写 options.html:

<div ng-controller="OptionsController">Options
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>
</div>

OptionsController 应该放在外部 html 元素中。

【讨论】:

  • 很好,我错过了。在原始 html 中,将其输入到标有控制器的 div 之外,因此范围变量不存在。
【解决方案2】:

我也面临同样的问题,

在 main 标记下它可以正常工作,但是当将一些数据绑定到 nav.html 时它不起作用。

找到这个链接

AngularJS - losing scope when using ng-include

inside 包括其工作子范围。 创建自定义指令的更好选择,其简单的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2017-02-02
    • 2015-08-01
    • 1970-01-01
    • 2018-03-27
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多