gpt4 book ai didi

javascript - 基本 Yeoman Angular Todo 应用程序中的范围问题

转载 作者:行者123 更新时间:2023-11-30 06:25:46 25 4
gpt4 key购买 nike

我正在按照此处的教程进行操作: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>

主要.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 注入(inject))。所以我只是将 ng-controller="MainCtrl" 从 index.html (Scope003) 中的 .container div 移动到 main.html 中的 .jumbotron div。

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

最佳答案

ng-include 创建一个新的作用域。因此,我将 ng-controller="MainCtrl"index.html (Scope003) 中的 .container div 移动到 main.html 中的 jumbotron div。

关于javascript - 基本 Yeoman Angular Todo 应用程序中的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com