gpt4 book ai didi

javascript - 为什么 $scope 会改变整个页面的值?

转载 作者:行者123 更新时间:2023-11-28 04:35:55 25 4
gpt4 key购买 nike

我正在学习 AngularJS,并且正在尝试制作一个待办事项应用程序。一切都很好,除了当我尝试添加新的待办事项时,之前的待办事项也会发生变化。我认为这是因为 $scope 在整个页面中更改了它的值,而我只想在刚刚生成的最后一个待办事项中更改它。也许我的代码对于这个目的来说是错误的,再说一遍,我刚刚开始学习 AngularJS。

希望你能帮助我,这是我的代码:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function ($routeProvider) {

$routeProvider

.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})

.when('/todo', {
templateUrl: 'pages/todo.html',
controller: 'subController'
})

});

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


}]);

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

$scope.getMsg = function(){

$scope.todoHeader = $('#header').val();
$scope.todoMsg = $('#msg').val();

var item = $compile("<todo-item todo-Title='{{todoHeader}}' todo-message='{{ todoMsg }}'></todo-item>")($scope);
$(".list-group").append(item);

}
}]);

myApp.directive('todoItem', function(){
return {
templateUrl: 'directives/todoItem.html',
scope: {
todoTitle: "@",
todoMessage: "@"
}
};
});
<h3>Todo Page</h3>

<div style="margin:auto;margin-bottom: 10px;display:table;">
<input type="text" id="header" placeholder="Enter todo header" style="margin-right:10px;padding:5px;"><br>
<textarea type="text" id="msg" placeholder="Enter todo message" style="margin-right:10px;padding:5px;"></textarea><br>
<button type="button" class="btn btn-primary" ng-click="getMsg()">Add Todo</button>
</div>

<div class="list-group" style="margin: auto; display: table;">
</div>

这是指令(todoItem.html)代码:

<a href="#" class="list-group-item list-group-item-action flex-column align-items-start" style="width:600px">
<div class="d-flex w-100 justify-content-between">
<h1 class="mb-1">{{ todoTitle }}</h1>
</div>
<p class="mb-1">{{ todoMessage }}</p>

最佳答案

是的,确实在您的 getMsg 函数中,您总是覆盖相同的 $scope todoHeadertodoMessage 变量。

这是变量在$scope中的默认行为,如果在$scope中声明变量将会在整个应用程序中共享,所以它是更改它会影响页面中所有出现的情况。

解决方案:

我认为你应该将你的 todos 存储在你范围内的一个数组中,每次将一个待办事项推送到其中,或者只制作两个 todoHeader todoMessage 位于您的 getMsg 函数中,并在新的 HTML 待办事项项中使用它们。

这就是您的代码:

//If you wanted to store the todos in an array
$scope.todos = [];

$scope.getMsg = function() {

var todoHeader = $('#header').val();
var todoMsg = $('#msg').val();

//or if you want to store the todos in an array
$scope.todos.push({
todoHeader: todoHeader,
todoMessage: todoMessage
});

var item = $compile("<todo-item todo-Title='+todoHeader+' todo-message='+todoMessage+'></todo-item>")($scope);
$(".list-group").append(item);
}

关于javascript - 为什么 $scope 会改变整个页面的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211037/

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