0

I love angularjs, but I get so confused with directives lol.

I have the following:

//postcode grabber
app.directive('postcodes',
    function ($rootScope, $http) {
        return function (scope, element, attrs) {
            element.bind('change', function () {
                var targetSuburb = scope.$eval(attrs.targetSuburb);
                alert(targetSuburb);
                var modal_element = angular.element('#myModal');
                var ctrl = modal_element.controller();
                var url = '/postage/postcodes/?suburb=' + element.val();
                ctrl.setModal(url);
                modal_element.modal('show');
            });
        };
    });

This my HTML:

<input type="text" class='form-control' ng-model="model.suburb" postcodes id='ca_suburb' target-suburb='ca_suburb' target-state='ca_state' target-postcode='ca_postcode'>

The alert is always "undefined" - Is there something I'm missing to be able to access the attributes correctly?

0

2 Answers 2

1

If you want to access the value of the model then

app.directive('postcodes', function ($rootScope, $http) {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, controller) {
            element.bind('change', function () {
                console.log(controller.$viewVaue)

                var modal_element = angular.element('#myModal');
                var ctrl = modal_element.controller();
                var url = '/postage/postcodes/?suburb=' + element.val();
                ctrl.setModal(url);
                modal_element.modal('show');
            });
        }
    };
});

Demo: Fiddle

If you are looking to alert ca_suberb then just use

    alert(attrs.targetSuburb);

Demo: Fiddle

If ca_suberb is a scope property then your code is working fine

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

@BenKilah what do you actually want to fetch here?
@BenKilah if you want the typed value then use ngModel as updated above - it will give you the value of the binded field
thanks! - where does controller.$viewVaue come from? couldn't find it in the docs.
0

If you want to get what is typed in, you should access via scope like this

alert(scope.model[attrs.targetSuburb]);

where attrs.targetSuburb should be the field name and it should be set like this since you define the model to be model.suburb

target-suburb='suburb'

2 Comments

re-used component, it's not always scope.model.suburb - thanks tho!
@BenKilah Updated. basically you need to tell the directive what is the field name

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.