Reputation: 8578
I'm trying create a CRUD page, using AngularJS, I using Angular Router UI for pages changes
How to can I access a variable in my main Controller
, in controller
of route?
//This is my main controller:
var app = angular.module('app', [
'ui.router'
]);
app.controller('MyCtrl', function ($scope) {
$scope.persons = [
{name: 'Daisy', description: 'Developer'},
{name: 'Zelda', description: 'Developer'},
{name: 'Luide', description: 'Developer'},
{name: 'Mario', description: 'Developer'}
];
});
This is my router config app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/');
$stateProvider
.state('list', {
url: '/list',
templateUrl: 'list.html',
controller: 'MyCtrl'
})
.state('edit', {
url: '/edit',
templateUrl: 'edit.html',
controller: function($scope, $state) {
$scope.person = {name: "", description: ""};
$scope.click = function () {
$state.go('list');
};
}
})
.state('add', {
url: '/add',
templateUrl: 'edit.html',
controller: function($scope, $state) {
$scope.person = {name: "", description: ""};
$scope.click = function () {
// HOW TO CAN I ACCESS $SCOPE.PERSONS FOR MAKE THIS PUSH?
$scope.persons.push($scope.person);
$state.go('list');
};
}
});
});
Upvotes: 2
Views: 1658
Reputation: 6958
Rather than create $scope.persons in a MainController, it would probably be better to use a service to store the persons object:
app.service("People", function () {
this.persons = [
{name: 'Daisy', description: 'Developer'},
{name: 'Zelda', description: 'Developer'},
{name: 'Luide', description: 'Developer'},
{name: 'Mario', description: 'Developer'}
];
});
Then you can inject this into your controllers (your code above):
.state('add', {
url: '/add',
templateUrl: 'edit.html',
controller: function($scope, $state, People) {
$scope.person = {name: "", description: ""};
$scope.click = function () {
//use persons object of people service.
People.persons.push($scope.person);
$state.go('list');
};
}
});
});
You can share these persons across different controllers, services, and directives through Dependency Injection. For instance, your list controller (MyCtrl) would look as follows:
app.controller('MyCtrl', function ($scope, People) {
$scope.persons = People.persons;
});
Upvotes: 4