Angular using ng-model with expression in directive template

后端 未结 2 810
小蘑菇
小蘑菇 2021-01-11 16:05

I want to use the ng-model attribute in a custom element. The problem is, that I need to set the ng-model with an expression:

ng-model=\"{{anyVariable}}\"
         


        
2条回答
  •  -上瘾入骨i
    2021-01-11 16:23

    I couldn't find a way to pass an expression to ng-model within the directive template.

    Following solution creates an isolated model within the directive and directive controller dynamically creates the property name in main controller model object and watches the isolated model to pass updates to main model:

    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('');
    
        };
    });
    

    Plunkr Demo

提交回复
热议问题