用另一个模型值替换模型中的字符串

时间:2015-03-30 20:21:09

标签: angularjs

我需要在另一个模型值中使用模型值,让我给你看一个样本。

我正在建立一个"教程"使用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然后以旧方式替换文本?

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

谢谢!

1 个答案:

答案 0 :(得分: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,以便AngularJS解析其中的指令(我们刚刚定义的answer)。

所以:

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