2017-05-26 61 views
1

我正在学习AngularJS,我试图制作一个todo应用程序。 除了当我尝试添加新的待办事项时,以前的待办事项也会发生变化,一切都很好。 我认为这是因为$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> 

+0

哪里是加入待办事项的代码? –

回答

0

确实在你的getMsg函数中你总是压倒性的e相同$scopetodoHeadertodoMessage变量。

而且这是在$scope变量的默认行为,如果一个变量在$scope宣布将在整个应用程序中共享,所以它的变化会影响页面中的所有的出现次数。

解决方案:

我想你应该你todos存储在你的范围数组,每一次推待办事项进去,或者只是让两个todoHeadertodoMessage您的本地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); 
} 
+0

它按照您的建议工作,但我想了解myApp.directive中的todoTitle和todoMessage的值是什么? 它们是todo-Title和todo-message属性中的值吗? – zb22

+0

他们将得到最后插入的值。 –

相关问题