AngularJS在编译时添加ng-model

时间:2014-06-19 18:42:15

标签: angularjs

我之前创建了一个名为click-to-edit

的指令

你会像

一样使用它
<click-to-edit="someValue">

其中$scope.someValue=7;

我已经意识到我需要使用ngModel控制器,如果我可以重新编译这个指令并将ng-model="someValue"添加到模板中,那将会更容易。我无法做到这一点,因为它给了我错误

"Error: [$compile:ctreq] Controller 'ngModel', required by directive 'clickToEdit', can't be found!"

这显然是因为我有

require:'ngModel'

到目前为止,这是代码片段

return {
      restrict: 'A',
      replace: true,
      require: 'ngModel',
      priority: 100,

      compile: function(tElement, tAttrs, transclude) {
          // Correct ngModel for isolate scope
              tAttrs.$set('ngModel', tAttrs.clickToEdit, false);
          }
          return {
              post: linkFn

          };
      },
      scope: {
          dp: '=?',
          type: '@',
          fn: '=?', //<--- formula
          editFn:'&?' // if you want to execute a function on a valid save, add this
      }

我只想做一个看起来像

的指令

<click-to-edit="model"/>
并将其更改为

<click-to-edit="model" ng-model="model"/>

然后让它按预期编译和工作。

如果您需要其他代码,请告诉我。

1 个答案:

答案 0 :(得分:1)

我不确定你是否考虑过这个 - 但为什么不这样做呢:

 <click-to-edit ng-model="model"/> 

要回答原始问题,我建议添加一个body指令:

.directive('body', function() {
  return {
    restrict: 'E',
    compile: function(element, attr) {
        $('[click-to-edit]', element).attr('ng-model', 'model');
    }
  }
})

Plunker Here