Evgeni
Evgeni

Reputation: 3343

Angularjs directive: how to find an element by dynamic id, and modify template

I'm trying to generate a form dynamically, based on a template which in turn has some dynamic properties.

I'm getting close, but having trouble retrieving a container element.

This is the directive:

myApp.directive('myDirective', function () {
    return {
    template: "<div> <label>{{Field.Name}} <div id='{{Field.Name}}_Container'></div> </label></div>",
    replace: true,
    restrict: 'AE',
    scope: {
        Field: "=fieldInfo",
        FieldData:"="
    },
    link: function (scope, element, attr) {
        var input = "<input type='" + scope.Field.Type + "' data-ng-model='FieldData[" + scope.Field.Name + "]' />";
        var inputEl = angular.element(input);
        var container = angular.element("#" + scope.Field.Name + "_Container"); // Doesn't work
        container.append(inputEl);
    }
}

});

Controller:

function MyCtrl($scope) {
    $scope.Fields = [
      { Name: "field1", Type: "text", Data:null },
      { Name: "field2", Type: "number", Data:null }
    ];

     $scope.FieldData = {}; //{fieldname: fielddata}
}

Html:

<div ng-controller="MyCtrl">
      <my-directive data-ng-repeat="field in Fields" data-field-info="field">
    </my-directive>
</div>

Basically I have fields descriptor objects, and need to generate a form based on that. I'm not quite sure how to reference a container object - does template has to be compiled before linking somehow ?

Also, I'm actually using templateUrl, if that matters.

And here's a fiddle.

Upvotes: 3

Views: 15450

Answers (1)

asgoth
asgoth

Reputation: 35829

You need to use $compile the compile to html template. Also, you can use element in the link function to access the outer div in your template.

var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function ($compile) {
    return {
        template: "<div> <label>{{Field.Name}} <div id='{{Field.Name}}_Container'></div> </label></div>",
        replace: true,
        restrict: 'AE',
        scope: {
            Field: "=fieldInfo",
            FieldData:"="
        },
        link: function (scope, element, attr) {
            var input = "<input type='" + scope.Field.Type + "' data-ng-model='FieldData[" + scope.Field.Name + "]' />";
            var html = $compile(input)(scope);
            element.find('div').append(html);
        }
    }
});

See jsfiddle.

Upvotes: 5

Related Questions