2

I am currently implementing Google's embedded maps into a project and created and angular directive for it.

I want to be able to update the url being used with values being passed in through attributes for the directive, however after changing the selected item, the value being displayed is always one behind the currently selected value.

Here is my link function:

function link (scope, element) {
    makeIFrame(scope, element);

    scope.$on('place-change', function () {
        makeIFrame(scope, element);
    });
}

And my makeIFrame function:

function makeIFrame(scope, element) {
    element[0].innerHTML = baseURL+scope.name +' '+ scope.zip; 
}

Here is a jsfiddle of the problem, I am just displaying an example of the url I would use: http://jsfiddle.net/t2GAS/60/

I am also wondering is there a better practice for performing tasks like this in a directive.

I tried using the template function but it did not access the values of the variables being passed and would try to parse the name of the variable instead.

EDIT:

Updated jsfiddle with Phil's answer: http://jsfiddle.net/t2GAS/64/

2
  • 1
    I'd say it's a digest cycle race-condition. Looks like the event broadcast reaches the directive before the scope is applied. Commented Jul 6, 2015 at 3:57
  • 1
    Re your "is there a better practice for performing tasks like this:" There absolutely is! Don't ever try to manipulate the DOM directly (by using e.g. innerHTML); by doing so you're bypassing most of what makes Angular worth using in the first place. Instead set values in the directive scope, and apply it in the template using something like <iframe ng-src="{{theVariable}}"></iframe> Commented Jul 6, 2015 at 14:17

1 Answer 1

2

Update to a recent version of Angular (1.3+) and change your directive link to use $scope.$watchGroup...

scope.$watchGroup(['name', 'zip'], function(values) {
    element.text(baseUrl + values.join(' '));
});

JSFiddle


Doing it this way, you no longer need an ng-change directive on your <select>

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

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.