我正在尝试使用AngularJS创建CRUD页面,我使用Angular Router UI进行页面更改
如何在我的主要Controller
路径的controller
中访问变量?
//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'}
];
});
这是我的路由器配置
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');
};
}
});
});
最佳答案
与其在MainController中创建$ scope.persons,不如使用服务来存储persons对象:
app.service("People", function () {
this.persons = [
{name: 'Daisy', description: 'Developer'},
{name: 'Zelda', description: 'Developer'},
{name: 'Luide', description: 'Developer'},
{name: 'Mario', description: 'Developer'}
];
});
然后,您可以将其注入到控制器中(上面的代码):
.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');
};
}
});
});
您可以通过依赖注入在不同的控制器,服务和指令中共享这些人。例如,您的列表控制器(MyCtrl)如下所示:
app.controller('MyCtrl', function ($scope, People) {
$scope.persons = People.persons;
});