【问题标题】:Scope problems in basic Yeoman Angular Todo App基本 Yeoman Angular Todo 应用程序中的范围问题
【发布时间】:2014-01-19 21:26:52
【问题描述】:

我正在学习这里的教程:http://www.youtube.com/watch?v=iUQ1fvdO9GY,同时学习 yeoman 和 angular。

我已经到了http://www.youtube.com/watch?v=iUQ1fvdO9GY#t=266 并且他的示例在哪里有效,但由于一些范围问题,我的没有。

main.html

<div class="jumbotron">
  <h2>My Todos:</h2>
  <p ng-repeat="todo in todos">
    <input type="checkbox" ng-model="todo.done">
    <span>{{todo.text}}</span>
  </p>

  <form ng-submit="addTodo()">
    <input type="text" ng-model="newTodoText" size="20">
    <input type="submit" class="btn btn-primary" value="add">
  </form>
</div>

main.js

'use strict';

var myApp = angular.module('todoAppApp');

myApp.controller('MainCtrl', ['$scope', function ($scope) {

    $scope.todos = [
        {text: 'Item 1', done: false},
        {text: 'Item 2', done: true},
        {text: 'Item 3', done: false}
    ];

    $scope.addTodo = function() {
        $scope.todos.push({text: $scope.newTodoText, done: false});
        $scope.newTodoText = '';
    };
}]);

不过,出于某种原因,newTodoText 变量位于 main.js 中 $scope 的子范围内。使用 Batarang 确认了这一点。由于缺乏代表,我无法发布图片,但在 Batarang,有:

Scope001 > Scope002 > Scope003(which is the $scope I have access to in the js) > Scope004 > {Scopes for each of the todos}

Scope003 具有原始的todos 数组和addTodo() 函数。当您在输入表单中键入时,Scope004 具有 newTodoText 文本。单击添加时,addTodo() 被正确调用,但 $scope 不包含 newTodoText,因为它在 Scope004 中。

由于我对框架的新颖性和这里几乎是准系统的实现,我显然在这里遗漏了一些简单的东西。我的 Google-fu 搜索结果很少。

编辑: 好的,所以在 index.html 中,它包含行

<div class="container" ng-include="'views/main.html'" ng-controller="MainCtrl"></div>

其中包括 main.html。我已经用包含在 div 中的 main.html 的文字内容替换了该行

<div class="container" ng-controller="MainCtrl">
    <!-- contents of main.html from above -->
</div>

神奇地解决了我的范围问题。为什么在单独的文件中包含 main.html 会混淆范围?

编辑#2

太好了,我想通了。

原来ng-include 创建了一个新范围,这与我的想法相反(我曾假设它等同于文字 html 注入)。所以我只是将ng-controller="MainCtrl" 从 index.html (Scope003) 中的 .container div 移动到 main.html 中的 .jumbotron div。

感谢您的帮助,我现在对范围更了解了!

【问题讨论】:

  • 似乎可以在this fiddle 工作- 还是我遗漏了什么?
  • 这段代码中一个潜在的混淆来源是有两个todo变量——输入模型和ngRepeat迭代器。 ngRepeat 创建它自己的范围 - 所以这两个 todo 变量在不同的范围内(如您所述)。不过,我个人会为两者使用不同的名称,以避免混淆。
  • KayakDave:你说得对,代码应该工作;事实上,当我对教程进行简单的 index.html+main.js 实现时确实如此,但由于某种原因,程序本身的结构是范围问题的根源。
  • 我已通过将 index.html 中的 ...ng-include="'views/main.html'"... 行替换为 main.html 的文字内容来修复范围问题,并且范围问题已得到修复。我已经更新了我上面的问题。为什么包含来自外部文件的 main.html 会影响范围?

标签: javascript angularjs angularjs-scope yeoman


【解决方案1】:

ng-include 创建一个新范围。所以我将ng-controller="MainCtrl"index.html (Scope003) 中的.container div 移动到main.html 中的.jumbotron div。

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多