Angular:使用指令创建问题

时间:2014-11-23 05:01:43

标签: javascript angularjs

我正在学习Angular,并试图掌握指令,我试图创建一个用于生成多项选择问题的指令。这就是我想要的工作:

<question type="multiple-choice"
          content="Hard tacos or soft tacos?"
          options="{{ [
            'Hard tacos!',
            'Soft tacos!',
            'Porque no los dos?'] }}"></question>

我不认为Angular会理解我试图传递问题指令的options属性的对象。

这是我的指令到目前为止的样子:

app.directive("question", function() {
  return {
    restrict: 'E',
    scope: {
      content: '@',
      options: '&'
    },
    templateUrl: function(elem, attrs) {
      return "partials/question-" + attrs.type + ".html";
    }
  }
}

这是我的模板(question-multiple-choice.html):

<h3 ng-bind="content"></h3>
<div ng-repeat="option in options()">
  <input type="radio" ng-value="option"> <span ng-bind="option"></span>
</div>

我收到以下错误,但我不知道如何继续:

Syntax Error: Token '[' is unexpected, expecting [:] at column 4 of the expression [{{ [
   'Hard tacos!',
   'Soft tacos!',
   'Porque no los dos?'] }}].

2 个答案:

答案 0 :(得分:3)

删除{{}}属性中的插值options

<强> DEMO

<question type="multiple-choice"
          content="Hard tacos or soft tacos?"
          options="[
            'Hard tacos!',
            'Soft tacos!',
            'Porque no los dos?']"></question>

此外,您的templateUrl回调attr.type中应该有attrs.type

的拼写错误

更新: 由于您希望将某个属性作为单选按钮的模型,为什么不使用ng-model范围表示法自行添加=属性。

<强> UPDATED DEMO

<强>问题-多choice.html

    <h3 ng-bind="content"></h3>
    <div ng-repeat="option in options()">
      <input ng-model="$parent.ngModel" type="radio" ng-value="option" name="option"> <span ng-bind="option"></span>
    </div>

<强>指令

app.directive("question", function() {
  return {
    restrict: 'E',
    scope: {
      content: '@',
      options: '&',
      ngModel: '='
    },
    templateUrl: function(elem, attrs) {
      return "question-" + attrs.type + ".html";
    }
  }
});

请注意,我在模板中使用了$parent.ngModel,因为ng-repeat会创建子范围。

答案 1 :(得分:0)

使用&#34; =&#34;而不是&#34;&amp;&#34; (用于传递函数)用于options属性。

然后,当您使用该指令时,从表达式中删除花括号。

&#34; =&#34;你想要用值进行双向绑定,在本例中是一个数组。