Reputation: 71
I need to add data from array in php to AngularJS. I tried:
HTML
<? foreach ($new->images as $val): ?>
<div ng-init="func(<?=$val?>)"></div>
<? endforeach; ?>
AngularJS:
$scope.addToSlide = function (src, desc){
obj = {};
obj.src = src;
obj.desc = desc;
$scope.photos.push(obj);
};
What is best way to do it?
Upvotes: 1
Views: 895
Reputation: 93
I have made some web apps with php and angularjs. The way I do it is the following:
When bringing data from php to an array in angular and html.
I can have this script in php:
<?php
require_once '../config.php';
$id = $_GET['id_project'];
$query = "SELECT *
FROM `activity_planned` as A,`user` as U
WHERE A.id_user = U.id_user and A.id_project = $id";
$answer = $mysqli->query($query);
$result = array();
foreach( $answer as $row ){
array_push($result,$row);
}
echo $json_response = json_encode($result);
?>
Then, the function in angular that calls this script uses the $http service:
$scope.getActivities = function() {
$http({
url: './scripts/getters/get-activities-by-project-id.php',
method: 'GET',
params: {
id_project: $stateParams.projectId
}
})
.success( function( response ) {
$scope.activities = response;
});
};
By having the ng-repeat directive in html, all these "activities" will be displayed:
<div ng-repeat="item in activities track by $index">
<p>{{item.id}}</p>
<p>{{item.name}}</p>
</div>
You will need to encode into json the array and echo the result in php.
This "echo" will function as a return, and the response parameter in the $scope function will receive the data from it.
Upvotes: 0
Reputation: 4611
did you try the following?
<div ng-init="images = <?=$images ?>"></div>
Upvotes: 0
Reputation: 14056
This is what you don't do with Angular - messing with HTML from outside.
The Angular way is to use simple Angular template and pull your data with Angular's services such as $http
.
Then Angular's $http
will send a request to your server and your PHP will respond with data (JSON), that Angular will receive and use.
Instead of foreach
you use ng-repeat
and ng-init
is generally not recommended (see the page for details).
Upvotes: 0
Reputation: 48883
ng-init is not really intended for what you are trying to do. The manual clearly states to only use it as part of ng-repeat.
And mixing php and javascript is challenging at best. Try to think more in terms of having php return json objects.
Also try to inject needed data as constants or values. Something like:
<script src="app.js"></script>
<script>
(function(angular) { 'use strict';
var appModule = angular.module('ceradSraApp');
appModule.constant('ceradApiPrefix','<?php echo $apiPrefix; ?>');
})(angular);
</script>
So ceradApiPrefix can now be injected wherever it's needed. Do whatever you need to do in php to boil your data down to a single echo.
Upvotes: 1