Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context.
This is the main file of my app:
var app = angular.module('app',
[
'matchCtrl',
'matchService',
'ngRoute'
]);
app.config(function($routeProvider){
$routeProvider
.when('/', { templateUrl: '../app/views/partials/home.html' })
// all routes for matches
.when('/matches', { templateUrl: '../app/views/partials/matches.html', controller: "matchController" })
.when('/matches/:id', { templateUrl: '../app/views/partials/match_place.html', controller: "matchController" })
.otherwise({ redirectTo: '/' });
});
In my application, there is a controller called matchController. The purpose of this controller is to fetch data using the get and show methods from my match factory.
Here is the controller:
angular.module('matchCtrl', [])
.controller('matchController', function($scope, $http, Match) {
// object to hold all the data for the new match form
$scope.matchData = {};
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the matches first and bind it to the $scope.matches object
Match.get()
.success(function(data) {
$scope.matches = data;
$scope.loading = false;
});
$scope.showPlaces = function(id) {
$scope.loading = true;
console.log($scope);
Match.show(id)
.success(function(data){
$scope.places = data;
console.log($scope.places);
$scope.loading = false;
});
};
});
Next, we have the factory. I am utilizing Laravel as an API Backend to retrieve data, and all routes "api/*" are defined in my Laravel routes file.
angular.module('matchService', [])
.factory('Match', function($http) {
return {
get : function() {
return $http.get('api/matches');
},
show : function(id) {
return $http.get('api/matches/' + id);
},
}
});
Shown below is my index file, along with the partial where I intend to utilize the $scope.place variable.
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Laravel and Angular test</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.min.js"></script>
</head>
<body class="container">
<div ng-view></div>
<script src="js/controllers/matchCtrl.js"></script>
<script src="js/controllers/placeCtrl.js"></script>
<script src="js/services/matchService.js"></script>
<script src="js/services/placeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The partial view looks like this:
<div class="place text-center">
<ul>
<li>{{ place.name }}</li>
</ul>
</div>
My issue lies in the fact that the $scope in the partial view differs from that in the main view. Consequently, I am unable to access the $scope.place variable and use it within the view.