Correct way of passing dynamic data to angularjs directive
I am developing an AngularJS directive that should work as a separate widget that can be customized by setting attributes as objects. My main tasks are below:
- Performs internal directive processing based on the object passed in attributes. Processing includes fetching the REST API response. I am using controllers for this.
- After my directive does some processing, it can change the object that my parent controller should change.
Below is some sample code that covers my purpose.
Using directive:
<post-listing page-id="currentPage.id" config="postConfig" posts="posts" />
Code for directive
'use strict';
angular.module('myApp')
.directive('postListing', function () {
return {
templateUrl: '/views/directive.post-listing.html',
restrict: 'EA',
scope: {
page_id:"=",
config:"=",
posts:"=",
},
controller: "DirectivePostListingCtrl"
};
});
Code for directive controller:
'use strict';
angular.module('myApp')
.controller('DirectivePostListingCtrl', function ($scope, $rootScope, $routeParams)
{
// Here I want to access the page_id and config as the actual value
// Here I will also update the posts array which is exposed to outside of directive.
});
Code for template:
<h4>Displaying Posts for {{page.title}}</h4>
<ul>
<li ng-repeat="p in posts" >{{p.title}}</li>
</ul>
When I run this code, it says $ scope.page_id is either "undefined" or it says "currentPage.id" (based on the selected = or @ operator), where I expect it to be the value of currentPage. id.
Please suggest.
Thanks in advance.
source to share
<post-listing data="PostListing" />
// use this in the controller
'use strict';
angular.module('myApp')
.controller('DirectivePostListingCtrl', function ($scope, $rootScope, $routeParams)
{
$scope.PostListing={}
$scope.PostListing.pageId=//Your Data
$scope.PostListing.config=//Your Data
$scope.PostListing.posts=//Your Data
});
Make changes to your directive
angular.module('myApp')
.directive('postListing', function () {
return {
templateUrl: '/views/directive.post-listing.html',
restrict: 'EA',
scope: {
data:"="
},
controller: "DirectivePostListingCtrl"
};
});
Use code in a template like
<ul>
<li ng-repeat="p in data.posts" >{{p.title}}</li>
</ul>
source to share
there are three main problems :
-
with @, the attribute must be an evaluated value . Therefore, he should attribute as follows:
page-id="{{currentPage.id}}"
. . See the best explanation here: fooobar.com/questions/11068 / ... . -
As @dfsq said, page_id should be pageId .
Here is a plunker with a solution : http://plnkr.co/edit/z843xZjIDQVe11edYLDR?p=preview
- Your custom directive must not be a void element . It is better to close the tag like
</post-listing>
to avoid strange behavior. In my case, chrome wraps everything inside the directive to the end of the div. Here is a plunker using transclude to show that my paragraph is wrapped inside a custom directive: http://plnkr.co/edit/H3mDdi631flnC8AG2Q8i?p=preview
source to share