AngularJS - Why is my directive isolated scope variable is undefined?
Solution 1
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.
Solution 2
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
}
}
});
Solution 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
Scottie
Updated on September 11, 2020Comments
-
Scottie almost 4 years
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 } } });
-
Bilal Mirza over 8 yearsDirective API has been moved to $compile.[docs.angularjs.org/api/ng/service/$compile]
-
The DIMM Reaper about 8 yearsExcellent answer explaining the difference in detail: stackoverflow.com/a/14063373/3123195