如何将包含[$ index]的字符串传递给我的指令?

时间:2014-01-06 16:38:28

标签: javascript angularjs

我正在尝试在指令调用中使用的数据属性上设置一些文本:

<textarea class="pagedown-admin wmd-preview-23"
   data-modal="modal"
   data-pagedown-admin
   data-ng-model="answer.text"
   data-pid="answer.answerId"
   data-field="{{'modal.data.answers[' + $index + '].text'}}"
   id="modal-data-answer-{{$index}}"></textarea>

无论我尝试什么,它都会出现语法错误。有谁知道什么可能是错的?我想从AngularJS ng-repeat中传入一个带有数组索引 value 的字段名称。

app.directive('pagedownAdmin', function ($compile) {
    var nextId = 0;
    var markdownConverter = new Markdown.Converter();
    var converter1 = Markdown.getSanitizingConverter();

    converter1.hooks.chain("preBlockGamut", function (text, rbg) {
        return text.replace(/^ {0,3}""" *\n((?:.*?\n)+?) {0,3}""" *$/gm, function (whole, inner) {
            return "<blockquote>" + rbg(inner) + "</blockquote>\n";
        });
    });

    return {
        require: 'ngModel',
        replace: true,
        scope: {
            field: '=field',
            modal: '=modal',
            pid: '=pid'
        },
        template: '<div class="pagedown-bootstrap-editor"></div>',
        link: function (scope, element, attrs, ngModel) {

后来在我的指令中我有:

            scope.$eval(attrs.field + "=" + rawContent);
            scope.$apply();

然而,在它给出错误之前,似乎没有达到执行$ eval的程度。

这是语法错误:

Error: [$parse:syntax] http://errors.angularjs.org/1.2.3/$parse/syntax?p0='modal.data.answers%5B'&…7D%7D&p4='modal.data.answers%5B'%20%2B%20%24index%20%2B%20'%5D.text'%7D%7D
    at Error (<anonymous>)
    at http://127.0.0.1:81/Scripts/angular-v1.2.3/angular.min.js:6:449

1 个答案:

答案 0 :(得分:0)

这是example

您应该这样写:

<textarea data-field="{{modal.data.answers[$index].text}}" >

但在引用时,您还应该使用文本绑定语法@)而不是双向绑定语法=)到父范围的field

scope: {
  field: '@',            
},

简而言之,"@"语法支持插值,而"="语法则不支持!

你一定要读这个What is the difference between '@' and '=' in directive scope in AngularJS?


我总是希望在可能的情况下显示源代码:

compile.js中有一个nodeLinkFn函数,在里面你可以看到这些情况:

case '@':
  attrs.$observe(attrName, function(value) {
    isolateScope[scopeName] = value;
  });
  attrs.$$observers[attrName].$$scope = scope;
  if( attrs[attrName] ) {
    // If the attribute has been provided then we trigger an interpolation to ensure
    // the value is there for use in the link fn
    isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  }
  break;

case '=':

  // ....... some code here

  isolateScope.$watch(function parentValueWatch() {

    //...... some code here

  }, null, parentGet.literal);
  break;

摘要: