0

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

1

2 Answers 2

1

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
      }
    }
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked with a little tweaking. An error was thrown due to the label attirbute "First Name:" After changing this to "First" and adding the "Name:" in the name template I got this to work.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.