由于每个问题都有自己的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
或其他)的实例中。