各単一の質問には独自のQuestionController
があり、 が設定されているQuestionController
場所で$scope.selected
あるため、相互に作用しません。つまり、編集をクリックすると、selected
その個別のコントローラーが設定されます。
これを修正する簡単な方法は、編集をクリックしたときに親スコープ (含まれているコントローラー) にプロパティを設定することです。
function MyCtrl($scope) {
$scope.questions = [];
$scope.AddRootQuestion = function(questions) {
questions.push({name: 'Question', nodes: []});
};
// added this method --v
$scope.setSelected = function(q) {
$scope.selected = q;
};
}
function QuestionController($scope) {
$scope.choices = [];
$scope.choice = {text: ''};
$scope.AddSubQuestion = function(question, $element) {
var newName = 'Name of question goes here';
question.nodes.push({name: newName, id: 'it goes in here', nodes: []});
};
// modified this method --v
$scope.editQuestion = function(question){
$scope.setSelected(question);
};
$scope.isSelected = function(question) {
return $scope.selected === question;
};
}
しかし、これはQuestionController
親コントローラーに依存します。はるかに優れた設計は、すべてのデータとデータ操作メソッドをサービスに移動することです。
var myApp = angular.module('myApp',[]);
myApp.factory('Question', function() {
return {
questions: [],
addRootQuestion: function() {
this.questions.push({name: 'Question', nodes: []});
},
addSubQuestion: function(question, data) {
question.nodes.push(data);
},
setSelectedQuestion: function(question) {
this.selectedQuestion = question;
},
isSelectedQuestion: function(question) {
return this.selectedQuestion == question;
}
};
});
次に、サービスをコントローラーに挿入できます。
function MyCtrl($scope, Question) {
$scope.questions = Question.questions;
$scope.AddRootQuestion = function() {
Question.addRootQuestion();
};
}
function QuestionController($scope, Question) {
$scope.choices = [];
$scope.choice = {text: ''};
$scope.AddSubQuestion = function(question, $element) {
var newName = 'Name of question goes here';
Question.addSubQuestion(question, {
name: newName, id: 'it goes in here', nodes: []
});
};
$scope.editQuestion = function(question){
Question.setSelectedQuestion(question);
};
$scope.isSelected = function(question) {
return Question.isSelectedQuestion(question);
};
}
例: http://jsfiddle.net/BinaryMuse/pZkBv/
必要に応じて、JavaScript OOP の原則を使用して、より豊富なデータ モデルを構築できます。たとえば、Question
質問を操作するためのメソッドを持つインスタンスを持つことができます。これは、それ自体がQuestionContainer
(またはSurvey
またはTest
または何でも) のインスタンス内に存在します。