I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page:
<div my-directive user="{{user.name}}"></div>
The user object is fetched from a JSON response after making an HTTP request using the $http service. However, when I debug the attribute.user value in my directive, it returns blank. If I set user.name to a static value like "hello", it works fine. I have also tried:
attributes.$observe('user', function(val){...})
but it did not work either. Could this be related to the asynchronous nature of the request? How can I resolve this issue? Any help would be appreciated!
Edit: Sharing a snippet of my directive code for reference
angular.module('myApp').directive('myDirective', function() {
return {
restrict: 'A',
scope: true,
link: function($scope, elem, attr) {
$scope.user = $.parseJSON(attr.user)
},
controller: ['$scope', '$rootScope', 'GlobalVariables', function($scope, $rootScope, GlobalVariables) {
$rootScope.hasSignedUp = GlobalVariables.hasSignedUp;
$rootScope.signUpId = GlobalVariables.signUpId;
$rootScope.$watch('hasVoted', function(newVal, oldVal) {
if(newVal === true) {
if($rootScope.signUpId == $scope.user.id){
$scope.text = 'Signed Up!';
}else{
$scope.text = 'Sign Up';
}
}else{
$scope.text = 'Sign Up';
}
});
}]
};
});