2015-03-30 45 views
0

我需要在另一个模型值内使用模型值,让我告诉你一个示例。用另一个模型值替换模型中的字符串

我正在构建一个“教程”应用程序,它使用JSON文件来配置所有问题/答案。

... 
"courses": [ 
    "lessons": [ 
     "questions": [ 
      { 
       "id": "uniqueIdOne", 
       "question": "What is your name?", 
       "answer" : "" 
      }, 
      { 
       "id": "uniqueIdTwo", 
       "question": "Great {{uniqueIdOne}}, this is some random text.", 
       "answer": "" 
      } 
     ] 
    ] 
] 
... 

我需要的是让教程编辑能够像样本一样在另一个问题{{uniqueIdOne}}中使用以前的答案的方法。

有一种方法可以做到这一点?或者我应该创建一个过滤器来解析字符串并循环JSON文件,直到找到相应的id,然后以旧的方式替换文本?

现在,应用程序根据问题呈现输入文件,以获得用相应模型映射的用户答案。

谢谢!

+0

欢迎堆栈溢出。如果您提供了一些当前正在使用的代码来呈现此JSON数据,则您的问题可能会更容易可视化并回答。您可以查看http://stackoverflow.com/help/mcve,获取有关如何使您的示例更易于遵循的提示。 – Claies 2015-03-30 20:30:34

+0

谢谢!当然,我会的。 – 2015-03-31 00:59:37

回答

0

是的,这是可能的,并且有多种方式可以完成同样的事情。

假设你有一个控制器设定ng-controller

$scope.questions = [ 
      { 
       "id": "uniqueIdOne", 
       "question": "What is your name?", 
       "answer" : "" 
      }, 
      { 
       "id": "uniqueIdTwo", 
       "question": "Great <answer question-id="uniqueIdOne" questions="questions"></answer>, this is some random text.", 
       "answer": "" 
      } 
     ]; 

module.directive('answer', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      questions: '=', 
      questionId: '=' 
     }, 
     replace: true, 
     template: '<span class="answer">{{ answer }}</span>', 
     link: function($scope) { 
      var question = _.find($scope.questions, {id: $scope.questionId}); 
      if(question) { 
       $scope.answer = question.answer; 
      } 
     } 
    }; 
}); 

哪里_.findlodash.find

现在,你需要确保你bind HTML当显示的问题,这样的指令(answer我们只是定义)在它们内部被AngularJS解析。

所以:

<div ng-repeat="question in questions"> 
    <span ng-bind-html="question.question"></span> 
</div> 
相关问题