2013-03-24 55 views
11

我想在自定義元素中使用ng-model屬性。問題是,我需要設置NG-模型的表達式:在指令模板中使用帶有表達式的ng-model的角度

ng-model="{{anyVariable}}" 

的問題是,我始終會盡快得到一個錯誤,我的表達添加到模板中的NG-模型屬性:

Error: Syntax Error: Token 'x.name' is unexpected, expecting [:] at column 3 of the expression [{{x.name}}] starting at [x.name}}]. 
    at Error (<anonymous>) 
    at throwError (http://localhost:9000/public/javascripts/angular.js:5999:11) 
    at consume (http://localhost:9000/public/javascripts/angular.js:6037:7) 
    at object (http://localhost:9000/public/javascripts/angular.js:6327:9) 
    at primary (http://localhost:9000/public/javascripts/angular.js:6211:17) 
    at unary (http://localhost:9000/public/javascripts/angular.js:6198:14) 
    at multiplicative (http://localhost:9000/public/javascripts/angular.js:6181:16) 
    at additive (http://localhost:9000/public/javascripts/angular.js:6172:16) 
    at relational (http://localhost:9000/public/javascripts/angular.js:6163:16) 
    at equality (http://localhost:9000/public/javascripts/angular.js:6154:16) 

使用的代碼:

function addFormFieldDirective(elementName, template) { 
    app.directive(elementName, function() { 
     return { 
      restrict: "E", 
      scope: {}, 
      replace: true, 
           // adds some extra layout 
      template: buildFormTemplate(template), 
      link: function(scope, elm, attrs) { 
       scope.x = attrs; 
      } 
     }; 
    }); 
} 
addFormFieldDirective("textfield", '<input id="{{x.id}}" ng-model="{{x.name}}" type="text" name="{{x.name}}" value="{{x.value}}" />'); 

回答

1

我無法找到一個方法來表達傳遞給ng-model指令模板內。

繼溶液創建指令和指令controller動態創建在主控制器模型對象中的屬性名稱內的分離的模型和手錶的分離的模型來更新傳遞給主模型:

app.directive("textfield", function() { 
    return { 
     restrict: "E", 
     scope: {}, 
     replace: true, 
     controller:function($scope,$attrs) { 
      $scope.x=$attrs; 

      $scope.$watch('directiveModel',function(){ 
       $scope.$parent.myModel[$attrs.name]=$scope.directiveModel; 
      }) ; 

      $scope.directiveModel=$attrs.value; 
     }, 
     template: buildFormTemplate('<input ng-model="directiveModel" id="{{x.id}}" type="text" name="{{x.name}}" value="{{x.value}}" />'); 

    }; 
}); 

Plunkr Demo

+0

這是另一個使用'ng-repeat'的版本,只有html中需要的屬性是用於從主控制器傳入元素的對象http://plnkr.co/edit/kcxFA7lrnlMoScrHYlAC?p=preview – charlietfl 2013-03-24 15:36:10

6

嘗試其中一個版本:

.directive('myDir', function() { 
    return { 
     restrict: 'EA', 
     scope: { 
        YYY: '=ngModel' 
        }, 
     require: 'ngModel', 
     replace: true, 
     template: '<input ng-model="YYY" />' 
    }; 
}); 
+0

Angular 1.0.8 does不接受函數作爲模板:'模板必須只有一個根元素。是:function render(element,attrs){return'';}' – maklemenz 2013-09-10 09:59:30

+0

正是我所需要的。謝謝@馬里克斯 – Som 2015-02-11 17:30:28