javascript - AngularJS call method inside $routeProvider -
javascript - AngularJS call method inside $routeProvider -
i'm newer in angularjs. have simple question, can't find answer. have code:
angular.module('app', ['app.controllers', 'ngroute']). config(['$routeprovider', function ($routeprovider) { $routeprovider.when('/users', {templateurl: '../pages/list.html', controller: 'userlistctrl'}). when('/user-details/:login', {templateurl: '../pages/form.html', controller: 'userctrl' /* , here need phone call userdetails(login) userctrl */}). otherwise({redirectto: '/users'});; } ]); app.controller('userctrl', function ($scope, $http, $location) { $scope.userdetails = function (login) { $http.get(url + login).success(function (data) { $scope.user = data[0]; console.log('tst'); }).error(errorcallback); }; $scope.createuser = function (user) { $http.post(url, user).success(function (data) { $location.path('/users'); }).error(errorcallback); }; });
my problem is: don't know how phone call specific method of controller when routing matches. need phone call method , give parameter :login routing. how solve this? answers
if understand correctly, re-using same controller 2 parts of view (or 2 views), 1 creating user , 1 fetching details of current user.
since these 2 aspects totally different, not advisable utilize same controller both. controllers should different , mutual or re-usable functionality should shared through service.
in case, code makes calls backend should not placed within controllers, services. e.g.:
app.service('usersrv', function ($http) { var url = '...'; this.userdetails = function (login) { homecoming $http.get(url + login); }; this.createuser = function (user) { homecoming $http.post(url, user); }; }); app.controller('userctrl', function ($scope, usersrv) { var login = '...'; var errorcallback = ...; // fetch user details upon initialiation usersrv.userdetails(login).success(function (data) { $scope.user = data[0]; }).error(errorcallback); }); app.controller('newuserctrl', function ($location, $scope, usersrv) { var errorcallback = ...; $scope.createuser = function (user) { usersrv.createuser(user).success(function (data) { $location.path('/users'); }).error(errorcallback); }; });
you could, also, utilize $routeprovider
's resolve
property "preload" user's details , pass userctrl argument.
javascript angularjs url-routing
Comments
Post a Comment