Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Directive scope undefined in controller without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I am trying to make an http request in my controller, but my $scope.dataSource
comes back as undefined
, and I am not sure why. I build the directive like this:
app.directive('users', function(){ return { restrict: 'E', templateUrl: '/templates/dashboard/config/users.html', scope: { dataSource: '@' }, controller: function($scope, $http){ $http({ url: $scope.dataSource }).success(function(data){ $scope.data = data; }); } }; });
And the html like this, but it doesn’t run the ajax request because the $scope.dataSource
is undefined
.
<users class="col-sm-4" data-source="/data/users.json"></users>
Answer
Move it to a watch function:
app.directive('users', function($http) { return { restrict: 'E', templateUrl: '/templates/dashboard/config/users.html', scope: { source: '@' }, link: function($scope){ $scope.watch('source', function(source) { if (dataSource !== undefined) { $http({ url: source }).success(function(data){ $scope.data = data; }); } }); } }; });
We are here to answer your question about Directive scope undefined in controller - If you find the proper solution, please don't forgot to share this with your team members.