I have created a basic directive:
angular.module('app').directive('field', function () {
return {
restrict: 'E',
template: '<div ng-click="clickElement()"><input id="{{inputId}}"></div>',
scope: {
inputId: '@'
},
controller: function ($scope) {
if (!$scope.inputId) {
$scope.inputId = 'xyz';
}
function logId() {
console.log($scope.inputId); // 'xyz'
console.log($scope); //$scope.inputId is undefined here (!!!)
}
logId();
$scope.clickElement = function() {
//$scope.inputId is also undefined here
}
}
}
});
Then I tried using it without specifying the inputId
like this:
<field></field>
When I use the directive, my $scope.inputId turns out to be undefined instead of 'xyz' as expected. Why is this happening? What can be done to ensure 'xyz' is set as default if inputId is not specified in directive usage?
P.S. The same issue occurs within the postLink
function.
EDIT:
Plunk: http://plnkr.co/edit/0mpcbrdUdafCMzATmCYZ?p=preview
Temporary workaround (demonstrating the desired behavior): http://plnkr.co/edit/G6gxQhgrteJBeNmR7yTX?p=preview