2017-05-26 60 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

他們將得到最後插入的值。 –

相關問題