12

I have the following plunker:

http://plnkr.co/edit/7YUpQ1tEjnUaX01txFcK?p=preview

When I run this, templateUrl is undefined in the scope. Why?

My assumption here is that it's trying to find a variable named template.html in the parent scope, but can't, so it's assigning it to undefined. If so, how do I pass this in as a string instead of a scope variable?

Html:

<body ng-app="myApp">  
   <div ng-controller="TestCtrl">
      <test-directive ng-model="testModel" 
                      template-url="template.html">
      </test-directive>
   </div>
</body>

.js

var app = angular.module("myApp", []);

app.controller("TestCtrl", function($scope) {
  $scope.testModel = {}
});

app.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            model: "=ngModel",
            templateUrl: "="
        },
        template: "<div ng-include='templateUrl'></div>",
        link: function (scope, element, attrs) {
           console.log(scope.templateUrl);  // <-- Shows as undefined
        }
    }
});
Scottie
  • 11,050
  • 19
  • 68
  • 109

3 Answers3

14

Just change the scope:

    scope: {
        templateUrl: "@"
    },

you'll get the output 'template.html'.

The key point is the difference between '=' and '@'. You can refer to https://docs.angularjs.org/guide/directive.

creeper
  • 499
  • 2
  • 17
3

I figured out my problem. I need to use @ instead of =.

app.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            model: "=ngModel",
            templateUrl: "@"
        },
        template: "<div ng-include='templateUrl'></div>",
        link: function (scope, element, attrs) {
           console.log(scope.templateUrl);  // <-- Works perfectly
        }
    }
});
Scottie
  • 11,050
  • 19
  • 68
  • 109
3

When you will use equal sign (=) into directive, you have to define this property under the $scope, other wise it does not work, It will produce error '' . see the angular document link. whether you can try templateUrl: "=?" or under the $scope.

According to angular document

<!-- ERROR because `1+2=localValue` is an invalid statement -->
<my-directive bind="1+2">

<!-- ERROR because `myFn()=localValue` is an invalid statement -->
<my-directive bind="myFn()">

<!-- ERROR because attribute bind wasn't provided -->
<my-directive>

To resolve this error, always use path expressions with scope properties that are two-way data-bound:

<my-directive bind="some.property">
<my-directive bind="some[3]['property']">

your solution is here plnkr

Shohel
  • 3,886
  • 4
  • 38
  • 75