JordanC
JordanC

Reputation: 131

angularjs dynamic templateurl values

I am trying to create a "name" directive that can host both first and last names.

the code i currently have is:

index.html

<div data-dm-name label="First Name:" info="first_name"></div>
<div data-dm-name label="Last Name:" info="last_name"></div>

directive:

angular
    .module('app.names.directive',[])
    .directive('dmName', [ directive ])

function directive() {
    return {
        restrict: 'E',
        scope: {
            label: '=',
            info: '='
        },
        templateUrl: '/assets/components/name_template.html'
    };
}

name_template.html

<div class="wizard-form-group">
    <div class="input-group">
        <label class="wizard-form-label" for="info">
            {{ label }}
        </label>
        <span class="input-field"
              data-ng-class="{
                  error: form.info.$dirty &&
                         form.info.$invalid,
                  focused: form.info.$focused
              }"
            >
            <input
                type="text"
                name="info"
                id="info"
                data-ng-model="info"
                data-ng-required="true"
                data-ng-focus="form.info.$focused = true"
                data-ng-blur="form.info.$focused = false"
            />
        </span>
    </div>
</div>

My problem is that I don't seem to be able to pass in the values for label and info into the template file. What am I doing wrong?

I have just started out using angular so hopefully this has a simple solution.

Thanks in advance

Upvotes: 0

Views: 162

Answers (2)

Syam Pillai
Syam Pillai

Reputation: 5217

in your directive function add a link function

function directive() {
return {
    restrict: 'EA',
    scope: {
        label: '=',
        info: '='
    },
    templateUrl: '/assets/components/name_template.html',
    link : function($scope, element, attrs){
      if(attrs.label){
        $scope.label = attrs.label
      }
      if(attrs.info){
        $scope.info = attrs.info
      }
    }
  };
}

Upvotes: 1

T J
T J

Reputation: 43156

Your directive is restricted to element, but you're using it as attribute. So you're directive isn't acting upon the element.

You should modify the DDO to:

function directive() {
  return {
    restrict: 'A', // attribute allowed
    scope: {
        label: '=',
        info: '='
    },
    templateUrl: '/assets/components/name_template.html'
  };
}

Upvotes: 0

Related Questions