Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing $scope in AngularJS factory?

I am new to AngularJS and find it very interesting, but I am a bit unclear about the following situation.

app.factory('deleteFac', function($http){  var factory = {};   factory.edit = function(id){   $http.get('?controller=store&action=getDetail&id=' + id).     success(function(data, status){         /**          got an error on the following          when i use return data; and i get data undefined          in the controller which i get it because its doing a ajax call         you don't get data until the call first.         **/         $scope.detail = data;       })     }  return factory; }) 

I am getting error when I assign to $scope and use return data, is there anyway I can assign the return data to the $scope?

like image 746
Bill Avatar asked Mar 03 '14 22:03

Bill


People also ask

How do you get the $scope in console?

scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .

What is $scope in AngularJS?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).

What is scope and $scope in AngularJS?

The $ in "$scope" indicates that the scope value is being injected into the current context. $scope is a service provided by $scopeProvider . You can inject it into controllers, directives or other services using Angular's built-in dependency injector: module.

What is $scope and $rootScope?

"$rootScope” is a parent object of all “$scope” angular objects created in a web page. $scope is created with ng-controller while $rootscope is created with ng-app .


1 Answers

You don't typically use $scope inside a factory, service or provider. Usually, you would return the promise (returned by $http) and then handle the promise in a controller (where you do have $scope).

factory.edit = function(id){     return $http.get('?controller=store&action=getDetail&id=' + id); } 

Controller function:

$scope.edit = function(id) {      deleteFac.edit(id).then(function(response) {         $scope.something = response.model;     }); } 
like image 184
Davin Tryon Avatar answered Oct 09 '22 14:10

Davin Tryon