Summary:
I'm attempting to take an id from the $scope of a view's controller and pass it to my directive which then makes some more http calls using that id.
Here's my controller and directive js:
app.controller('MainCtrl', function(postsFactory) {
_this = this;
postsFactory.get({ id: $state.params.id}).$promise.then(function(res){
//assign the response to this controller as a post and
//output the controller on the view as editPostCtrl.
_this.post = res;
_this.idOfPost = _this.post.id;
// the post.id does exist
});
});
app.directive('foo', function() {
return {
restrict: 'E',
scope: {
postId: '=postId',
},
controller: function($scope) {
//make some more http calls with the postId
},
link: function(scope, element, attr) {
scope.$watch('postId', function(newVal) {
if(newVal) { postId = newVal;}
});
}
};
});
The view:
<body ng-controller="MainCtrl as mainCtrl">
<foo post-id="mainCtrl.idOfPost"></foo>
</body>
Issue:
The id never makes it to the view. When I inspect element and look at the directive's attribute, I see
post-id="mainCtrl.idOfPost"
Since I make a call to get the id in the main view's controller and bind it to the controller using the 'ctrl as' syntax, I saw I need to watch for it in the directive because the the main view's controller will return a promise: see this for ref: Directive is being rendered before promise is resolved
Well, this didn't work for me. However, I did find that using the watch method and also wrapping the directive in an ng-if would work:
<div ng-if="main.idOfPost">
<foo post-id="mainCtrl.idOfPost" ></foo>
</div>
However, this seems unnecessary to have logic in the view like this and makes the directive harder to use. I'm just not sure how to resolve it in the js. Any suggestions is appreciated.