Dynamically inject resource into controller - angularjs

It works:

function DetailsCtrl($scope, Plan){ $scope.entities = Plan.query(); } 

It does not mean:

 function DetailsCtrl($scope){ var injector = angular.injector(['myApp.services']); var name = 'Plan'; var Entity = injector.get(name); $scope.entities = Entity.query(); } 

In the second case, an error does not occur, and console.log ($ scope.entities) resets the loaded objects. BUT variables are not displayed in the template. I assume that the template loads before the mileage $ is filled with vars. If so, how can I guarantee that $ scope will be loaded in time in time?

+4
source share
2 answers

I created a service to dynamically load resources:

service:

 var m = angular.module('myApp.services', ['ngResource']). factory('Entity',function($resource){ return { Plan: $resource('/api/plans/:id',{id: '@id'}) } }). value('version', '0.1'); 

controller:

 function DetailsCtrl($scope, Entity){ $scope.entities = Entity['Plan'].query(); } 
+5
source

Yes it is. Angular templates are loaded regardless of whether the scope will receive data from resources or http calls. In my opinion, Angular either listens for the $ scope variable, or has some magic methods, and starts reloading the template rendering.

In this situation, it is possible that Angular recognizes that the shared resource service (the Plan model) is being transferred, and it expects it to be used to extract some data. Although in the second example, Angular has no idea that you are going to use another service internally, so it does not prepare any callbacks or checks for the $ scope variable.

If for some reason you set the value of the $ scope variable and Angular does not notice the change, you can immediately update your template, and then you can call this:

 $scope.$digest(); //or $scope.$apply(); 

The only problem is that it causes errors and errors if you cause it when it is already performing a digest operation (just use the try / catch branches around the statement).

If this does not work, you will need to double check to make sure the template itself has the correct syntax for the expressions.

+1
source

Source: https://habr.com/ru/post/1433290/


All Articles