I have a code that I get data of a JSON file in it using $http.get
. Now I wanna access the data in the custom directive that I've made !
Here is my code for the getting json file :
$http.get('myData.json').then(function(dataList){
for (var i = 0; i < dataList.data.length; i++) {
this.myData = {};
this.myData.id = dataList.data[i].id;
this.myData.car = dataList.data[i].car;
this.myArray.push(this.myData);
}
});
And here is my code for my custom directive :
app.directive('dataList', function(){
return {
restrict: 'E',
templateUrl: 'data-list.html'
};
});
It will be much more better if I could access the myArray data in the directive as a function and etc ...
Add a scope variable:
app.directive('dataList', function(){
return {
restrict: 'E',
scope: {
data: "="
},
templateUrl: 'data-list.html'
};
});
Pass it to your directive:
<data-list data="myArray">
Then you can access it in your template of the directive data-list.html:
<div ng-repeat="item in data">
Note: In your for-loop you are resetting your this.myData object each time, while you push it n-times in your array. Every item in your array will therefore be an empty {} object, except for the last one. Also, you are using the index i on your new object, which seems weird to me.
Instead create a new object in your for-loop:
for (var i = 0; i < dataList.data.length; i++) {
var myData = {};
myData.id = dataList.data[i].id;
myData.car = dataList.data[i].car;
myArray.push(myData);
}
Or maybe it is enough to just do this.myArray.push(dataList.data[i]), or even just assign the whole array: this.myArray = dataList.data
You can do it the following:
myApp.directive('dataList', function() {
return {
restrict: 'E',
scope: {
array: '='
},
template: '<div ng-repeat="o in array">ID: {{o.id}}<br/>Car: {{o.car}}</div>'
};
});
Here $scope.myArray (in your case it comes frop your $http.get request):
$scope.myArray = [
{ id: 1, car: "Car1" },
{ id: 2, car: "Car2" },
{ id: 3, car: "Car3" }
];
You can use it like this:
<data-list array="myArray"></data-list>
As a side note, I would suggest you to modify a bit the loop where you create myArray:
for(...) {
this.myArray.push({id: dataList.data[i].id, car: dataList.data[i].car});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With