I am trying to avoid the use of $scope in my angular controller (as suggested in a best practices tutorial). In the controller, I'm setting testVariable. In the directive, I'm returning the template, including testVariable, but this added variable does not output any value. This code is based on what I've found in the AngularJS documentation.
Below is my javascript code:
(function(angular) {
'use strict';
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
var _controller = this;
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
_controller.testVariable = "Test Variable!"
}])
.directive('myCustomer', function() {
return {
template: 'Name: {{customer.name}}<br />Address: {{customer.address}}<br />Value Here: {{ testVariable }}'
};
});
})(window.angular);
Here is the HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-directive-simple-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="docsSimpleDirective">
<div ng-controller="Controller">
<div my-customer></div>
</div>
</body>
</html>
I set up a plunkr for this here.
If you use controllerAs and bindToController
it will simplify your directive and then access testVariable
angular.module('docsSimpleDirective', [])
.controller('Controller', [function () {
this.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
this.testVariable = "Testing data here!"
}])
.directive('myCustomer', function () {
return {
template: 'Name: {{$ctrl.customer.name}}<br />Address: {{$ctrl.customer.address}}<br />Value Here: {{ $ctrl.testVariable }}',
controller: 'Controller',
controllerAs: '$ctrl',
bindToController: true
};
});
You can further simplify your directive if you use .component
to create docsSimpleDirective