Angular using ng-model with expression in directive template

后端 未结 2 809
小蘑菇
小蘑菇 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条回答
  • 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('<input ng-model="directiveModel" id="{{x.id}}" type="text" name="{{x.name}}" value="{{x.value}}" />');
    
        };
    });
    

    Plunkr Demo

    0 讨论(0)
  • 2021-01-11 16:36

    Try a version of this:

    .directive('myDir', function() {
        return {
            restrict: 'EA',
            scope:    {
                        YYY: '=ngModel'
                      },
            require:  'ngModel',
            replace:  true,
            template: '<input ng-model="YYY" />'
        };
    });
    
    0 讨论(0)
提交回复
热议问题