How to pass object from controller to directive without using $ scope in angularjs
Plunger link: http://plnkr.co/edit/j7BeL72lwHISCIlwuAez?p=preview
In the link above, I am using $ scope to pass data. But I want to use a model approach and replace $ scope.data in MainController with this.data p>
var app = angular.module ('plunker', []);
app.controller('MainCtrl', ['$scope',
function($scope) {
$scope.data = [{
time: '8/19/2014',
id: 123,
text: 'first'
}, {
time: '8/18/2014',
id: 456,
text: 'second'
}, {
time: '8/17/2014',
id: 123,
text: 'third'
}];
}
]);
app.directive('scrollGrid', [
function() {
return {
restrict: 'AE',
scope: {
data: '='
},
templateUrl: 'mainScroll.html',
controller: 'gridController',
controllerAs: 'gridCtrl'
}
}
]);
app.controller('gridController', ['$scope',
function($scope) {}
])
+3
source to share
1 answer
You can read more about the "Controller as syntax" syntax here: http://toddmotto.com/digging-into-angulars-controller-as-syntax/
Please note that this syntax was introduced in angular 1.2. Your plunkr was using angular 1.0.x.
Here is a plunkr example: http://plnkr.co/edit/5ddLyuRlyCt4PqulpOJG
The markup has been changed as follows:
<body ng-controller="MainCtrl as ctrl">
{{ctrl.data}}
<scroll-grid data="ctrl.data"></scroll-grid>
</body>
The controller has been changed as follows:
app.controller('MainCtrl', function() {
this.data = [
{
time: '8/19/2014',
id : 123,
text : 'first'
},
{
time: '8/18/2014',
id : 456,
text : 'second'
},
{
time: '8/17/2014',
id : 123,
text : 'third'
}
];
});
Let me know if you still have problems
+2
source to share