1

我正在创建一个指令,我想在其中比较存储在模型中的值(比如“名称”作为模型,它的值是“Angular”)存储在变量中。

我尝试了类似下面的东西,

var nameValue=name;

但它(nameValue)没有值“Angular”

Example:

app.directive('kmRadio', function() {

  return{
    restrict:'E',
    compile: function(element,attrs) {
      var model=ngModelName;     

      console.info(attrs.kmModel);
      console.info("{{'+attrs.kmModel+'}}");

      if(attrs.kmTitle==model) {
        previewString="<input type="+"radio"+" checked>";
      }
      else {
        previewString="<input type="+"radio"+">";
      }

      var htmlText=''+previewString+''+

        element.replaceWith(htmlText);
    }
  }
}) 

谁能告诉我如何检索存储在模型(ng-model)中的值

4

2 回答 2

0

您可以将指令范围内的属性链接到具有该scope属性的父级。可以在此处找到详细说明:AngularJS 中指令范围内的“@”和“=”有什么区别?

本质上添加

返回{限制:'E',范围:{kmModel:'=kmModel'}编译:函数(元素,属性){var model=ngModelName;

  console.info(attrs.kmModel);
  console.info("{{'+attrs.kmModel+'}}");

  if(attrs.kmTitle==model) {
    previewString="<input type="+"radio"+" checked>";
  }
  else {
    previewString="<input type="+"radio"+">";
  }

  var htmlText=''+previewString+''+

    element.replaceWith(htmlText);
}

}

会解决你的问题。

于 2014-04-23T13:53:21.453 回答
0

ng-checked您可以使用, 和链接功能简化一些事情:

app.directive('kmRadio', function() {
  return {
    restrict: 'E',
    scope: true,
    replace: true,
    template: "<input type='radio' ng-checked='title == model' />",
    link: function(scope, element, attrs) {
      scope.model = scope.$eval(attrs.kmModel);
      scope.title = attrs.kmTitle;

      console.info('attrs.kmModel: ', attrs.kmModel);
      console.info('scope.$eval(attrs.kmModel):', scope.model);
    }
  }
})

这是一个工作演示:http ://plnkr.co/edit/owTLnPUbbZIhwUtfoivt?p=preview

于 2014-04-23T19:33:45.400 回答