Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Why is my directive isolated scope variable is undefined?

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
        }
    }
});
like image 376
Scottie Avatar asked Sep 11 '14 02:09

Scottie


1 Answers

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.

like image 188
creeper Avatar answered Sep 30 '22 18:09

creeper