A
A
Artur Aralin2014-03-13 17:37:16
Angular
Artur Aralin, 2014-03-13 17:37:16

How to separate logic in AngularJS?

Hello! After searching on Google and not finding anything sensible, I am writing here! The question is: How to separate logic in AngularJS?
My code

function MainCtrl($scope, $http) {

  $scope.user = function($http) {
    /* Variables */
    var auth = false; //auth status
    var id = 33; //user id
    var name = ''; //user name
    var lname = ''; //last user name

    this.abc = 'some text';
    /* Methods */
  }; 
  /* end scope user */

  /* init */
  console.log($scope);
}

The variable "abc" is visible in $scope, but the variables inside the anonymous function cannot be reached.
console.log($scope.user.id); //выдает undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-03-13
@ArturAralin

I think it's too early for you to take up angular, since you still don't know what closures, objects, functions, function context are...

$scope.user = {
    auth: false,
    id: 33,
    name: '',
    lname: ''
    abs = 'some text'
}

but for the future: try to encapsulate logic in services. That is, if services like $http are injected into your controllers, then something obviously went wrong at the design stage. All this should be used inside your services, and controllers should not know anything about where the data comes from.
Ideally it should be something like this:
angular.module('app', [])

.controller('MainCtrl', function ($scope, userRepository) {
    userRepository.getUser().then(function (user) {
          $scope.user = user;
    });
})

.factory('userRepository', function ($http, $q) {
    return {
        // метод возвращающий данные пользователя
        getUser: function() {
              // забираем данные с сервера
              return $http(/** опции запроса */).then(function (response) {
                  return response.data; // возвращаем данные пользователя
              });
        }
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question