Issue
Having an issue with trying to pass some scope data from my app controller to directive
(function () {
'use strict';
angular
.module('app', [])
.controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
.directive('services', [
function () {
return {
restrict: 'E',
scope: {
testData: '='
},
template:
'<h2 class="service-name">Test: {{testData}}</h2>'
};
}
]);
/**
* Home controller.
* @param {*} $scope
*/
function HomeCtrl($http, $scope) {
$scope.testData = 'name';
}
})();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css" />
<script src="lib/script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="HomeCtrl">
<services testData="testData"></services>
</div>
</body>
</html>
I’m getting undefined for the scope "=" variable, testData
I can get it to render in the app using {{testData}}, but when passing it as an attribute, the directive is not receiving the value.
Solution
Here is your show code example modify to pass scope data to directive.
(function () {
'use strict';
angular
.module('app', [])
.controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
.directive('services', [
function () {
return {
restrict: 'E',
scope: {
testData: '@testData' // ****************** note here
},
template:
'<h2 class="service-name">Test: {{testData}}</h2>'
};
}
]);
/**
* Home controller.
* @param {*} $scope
*/
function HomeCtrl($http, $scope) {
$scope.testData = 'name';
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="HomeCtrl">
<!-- // ****************** note here -->
<services test-Data="Hello World!"></services>
</div>
</body>
Answered By – Thomson Mixab
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0