Ryan de Kock
Ryan de Kock

Reputation: 235

angularjs directive, cannot pass variable

So I am trying to inject a dynamic template into a page using angularjs. I initially tried to use ng-include which is great, however I require two way binding of the $scope & ng-include makes its own local copy so that cannot be used.

I have since tried to create a custom directive to load content dynamically, this works as expected when data is hard coded, however when I try pass a variable to the directive, it passes literally what is typed and not the value of the variable.

Controller

$scope.test = 'Yes!'

Directive

Basically, I would like the templateUrl to have a dynamic value

materialAdmin.directive("prospectiveModal", function () {


var dynamicUrl = function(scope, element, attributes) {

            console.log('directive')
            console.log('scope')
            console.log(scope)
            console.log('element')
            console.log(element)
            console.log('attributes')
            console.log(attributes)
            return 'views/prospectives/options/booked.html'
        };

return {
    restrict: 'EA',
    scope: {
        'test': '=test',

    }
    ,
    templateUrl: dynamicUrl

};

})

HTML

            {{test}}}
        <div prospective-modal test="{{test}}"></div>

console.log output is below

prospectiveModal:""
test:"{{test}}"

If I change the html to something like

<div prospective-modal test="test"></div>

then console.log is

test:"test"

How can I get the value of the variable inside of the directive? It must be possible right?

Upvotes: 0

Views: 145

Answers (1)

Ryan de Kock
Ryan de Kock

Reputation: 235

So I found a way to do this.

If you call ng-include in the view, it will create a local scope copy. However it seems if you create it inside the directive, it does not. So I did something like this:

materialAdmin.directive("prospectiveModal", function () {

return {
    restrict: 'EA',
    scope: false,
    template: "<div ng-include='subMenu[subOption].path'></div>"

};

})

Then in the view

<prospective-modal ></prospective-modal>

$scope has access to subMenu[subOption].path so when that value is changed, so is the template.

Upvotes: 0

Related Questions