I am working on Symfony3 and Angular 1.5.8 integration, the api part is all ready and now I am trying to display the result in partials using angular js which I am not having any success with.
This is my factory which is responsible for fetching data from symfony
jobs.fac.js
(function () {
"use strict";
angular
.module("ngListings")
.factory("jobFactory", function ($http) {
console.log('inside the factory');
function getJobs() {
return $http.get(Routing.generate("get_jobs"));
}
return {
getJobs: getJobs
}
})
})();
This is my controller jobs.ctrl.js
(function () {
"use strict";
angular
.module("ngListings")
.controller("jobsCtrl", function ($scope, $state, $http, jobFactory) {
var vm = this;
$scope.$on
vm.jobs;
jobFactory.getJobs().then(function (jobs) {
vm.jobs = jobs.data;
});
});
})();
this is my main.js where i am setting up the states and the controllers that are linked with the states
angular
.module("ngListings", ["ui.router"])
.config(function ( $stateProvider) {
$stateProvider
.state('jobs',{
url: '/listings/jobs',
templateURL: '/partials/home.html',
controller: 'jobsCtrl as vm'
})
;
});
Now this is my index where i am adding ui-view
{% extends 'base.html.twig' %}
{% block body %}
<ui-view></ui-view>
{% endblock %}
Now as I mentioned I am using Symfony so I have tried adding the partials inside the web directory and also inside the AppBundle/Resources/views/jobs/template-name in both cases the partial does not appear and there is no error in console either.
In console I can see the call being made to the URL and data being returned but its not being displayed in browser.
I will really appreciate if someone can tell me what am i missing here?
Note: Symfony and Angular are not setup separated, angular js files are kept in AppBundle and then being dumped in web directory, this is just for symfony users ofcourse any non symfony user who can see what i am doing wrong is also welcome to comment
To serve a template through Symfony you need a route/controller to access it via url ("partials/home.html" in your example). Elegant solution is to have one controller which is taking name of the partial as variable, and render that twig file as response. Take a look at this slide http://www.slideshare.net/mladenplavsic/symfony-angularjs-dafed26/19 as example of Template contoller.
With this you could change your templateUrl to something like "/template/home.html" where "home" is "$name" value for Symfony controller.
Related
I'm using Angular on Django with Apache. And I have an app like the following:
(function(){
'use strict';
angular
// AngularJS modules define applications
.module('app', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "/static/app/foo/templates/main.html"
})
.when("/red", {
templateUrl : "/static/app/foo/templates/red.html"
});
});
function foo() { }
})();
I'm serving my site on: http://localhost/ok/
When I make a GET to http://localhost/ok/ or to http://localhost/ok, all it's fine and the URL is transformed respectively to http://localhost/ok/#!/ or to http://localhost/ok#!/.
In main.html I have a link to the red "anchor" Go to Red. It points to http://localhost/ok/#red but when I click it, red.html is not returned, and I read in the address bar http://localhost/ok/#!/#red or http://localhost/ok#!/#red (depending on the URL pattern of the first call).
I do not understand where the problem is. How can I fix?
Try this:
Go to Red
Well, this is giving this angular newbie some gray hairs:
My regular isotope external javascript initialization begins like normal :
$(document).ready(function() {
// ISOTOPE INITIALISATON AND STUFF HERE
And that all works fine with no angular. Now since my isotope items is in a separate portfolio.html page which loads into my main index.html page which contains an ng-view div, isotope sometimes fails to initialize.
It's around fifty fifty: If I refresh isotope works, then it doesn't. So this is due to that angular is not ready renderinng the DOM. And so even though I am waiting for document ready (and tried document load), that does not work either.
Is there a simple way that I can create my isotope AFTER that my index.html page loaded my portfolio.html page in (where my portfolio contains my isotope divs), with Angular?
Please note I am not using angular-isotope but just the regular metafizzy isotope and angular.
A simple as possible solution would be great:
Somehow I must create my isotope after that the Angular is done. But how do I call a method in my main.js file(which is the file where I initialize my Isotope) from my Script.js file (which is the file with my Angular script)
If it is any help this is my angular script:
// script.js
// create the module and name it scotchApp
// also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
Hmmm.hmmmm. I think it is time for a cup of tea. Hmm. hmm
Look forward to your replies!
I solved it myself.
I simply added this line to my isotope javascript file
$(window).load(function() { window.setTimeout(onRenderReadyStartIsotope, 0) });
And the intialised isotope with that timedout function call. Was no need for me this time to look into directives or change the angular, the DOM now renders, the isotope begins.
I am trying to run an $http function when my AngularJS application first loads.
This $http function needs to finish before any of the controllers in my application could properly function. How would I go about doing this? This sounds like a promise, but it sounds like I would be creating a promise in each controller...
I currently have the function that I want to run first like this:
app.run(function() {
$http.get('link').success(function(data) {
// success function. The data that I get from this HTTP call will be saved to a service.
}).error(function(error) {
});
});
However, sometimes the controller will load before the http call finishes.
The problem
Angular is not dynamic, you cannot add controller dynamically neither factory, etc. Also you cannot defer controller bootstrap, angular loads everything together, and it's quite disadvantage (will be fixed in Angular 2)
The cure
But javascript itself has very important feature - closure, which works anywhere, anytime.
And angular has some internal services that can be injected outside of angular ecosystem, even into browser console. Those services injected as shown below. We technically could use anything else (jQuery.ajax, window.fetch, or even with XMLHttpRequest), but let's stick with total angular solution
var $http_injected = angular.injector(["ng"]).get("$http");
The act
First of all, we defer whole angular app bootstrap, inject http service. Then you make your needed request, receive data and then closure get's to work, we pass received data into some service, or we could also assign in to some angular.constant or angular.value but let's just make demo with angular.service, so when your service has data, bootstrap whole app, so that all controllers get initialized with your needed data
Basically that kind of tasks solved like this
<body>
<div ng-controller="Controller1">
<b>Controller1</b>
{{text}}
{{setting.data.name}}
</div>
<hr>
<div ng-controller="Controller2">
<b>Controller2</b>
{{text}}
{{setting.data.name}}
</div>
<script>
//define preloader
var $http_injected = angular.injector(["ng"]).get("$http");
$http_injected.get('http://jsonplaceholder.typicode.com/users/1').then(function(successResponse) {
//define app
angular.module('app', []);
//define test controllers
//note, usually we see 'controller1 loaded' text before 'settings applied', because controller initialized with this data, but in this demo, we will not see 'controller1 loaded' text, as we use closure to assign data, so it's instantly changed
angular.module('app').controller('Controller1', function($scope, AppSetting) {
$scope.text = 'controller1 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
angular.module('app').controller('Controller2', function($scope, AppSetting) {
$scope.text = 'controller2 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
//define test services, note we assign it here, it's possible
//because of javascript awesomeness (closure)
angular.module('app').service('AppSetting', function() {
this.setting = successResponse;
});
//bootstrap app, we cannot use ng-app, as it loads app instantly
//but we bootstrap it manually when you settings come
angular.bootstrap(document.body, ['app']);
});
</script>
</body>
Plunker demo
You can do this when you configure your routes
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'main.html',
resolve: {
data: ['$http',
function($http)
{
return $http.get('/api/data').then(
function success(response) { return response.data.rows[0]; },
function error(reason) { return false; }
);
}
]
}
});
}]);
Similar question:
AngularJS - routeProvider resolve calling a service method
AngularJS: $routeProvider when resolve $http returns response obj instead of my obj
Heres a plunkr I found using a service, which is what I would recommend.
http://plnkr.co/edit/XKGC1h?p=info
I have the following URL:
http://myUrl.com/#/chooseStyle?imgUpload=6_1405794123.jpg
I want to read the imgUpload value in the query string - I'm trying:
alert($location.search().imgUpload);
But nothing alerts, not even a blank alert - but console reads:
$location is not defined
I need this value to add into a controller to pull back data, and also to carry into the view itself as part of a ng-src
Is there anything I'm doing wrong? this is my app config:
capApp.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(false);
$routeProvider
// route for the home page
.when('/', {
templateUrl : '/views/home.html',
controller : 'mainController'
})
// route for the caption it page
.when('/capIt', {
templateUrl : '/views/capIt.html',
controller : 'mainController'
});
}):
This is the view:
<div class="container text-center">
<h1 class="whiteTextShadow text-center top70">Choose your photo</h1>
</div>
<script>
alert($location.search().imgUpload);
</script>
Main controller:
capApp.controller('mainController', function($scope) {
$scope.message = 'Whoop it works!';
});
My end goal is that I can find a solution to capturing and re-using data from the query string.
I will also mention, this is only my first week in Angular, loving it so far! A lot to learn...
<script>
alert($location.search().imgUpload);
</script>
You're making two mistakes here:
executing code while the page is loading, and the angular application is thus not started yet
assuming $location is a global variable. It's not. It's an angular service that must be injected into your controller (or any other angular component). This should cause an exception to be thrown and displayed in your console. Leave your console open always, and don't ignore exception being thrown.
You should not do this
<script>
alert($location.search().imgUpload);
</script>
// you need to inject the module $location
//(either in service, or controller or wherever you want to use it)
// if you want to use their APIs
capApp.controller('mainController', function($scope, $location) {
$scope.message = 'Whoop it works!';
//use API of $location
alert($location.search().imgUpload);
});
I have a basic app, that fetches some data through the $http service, however it doesnt render the data correct in the template, when the template is served from the template cache. My code looks like this:
angular.module('app', [])
api service:
.factory('api', function($http, $q) {
return {
getCars: function() {
return $http.get('api/cars');
}
};
})
the controller using the service:
.controller('carsCtrl', function($scope, api) {
api.getCars().success(function(data) {
$scope.cars = data;
});
})
the route setup:
.config(function($routeProvider) {
$routeProvider.when('/cars', {
templateUrl: 'cars.html',
controller: 'carsCtrl'
});
});
and the template cars.html
<div ng-repeat="car in cars">
{{ car }}
</div>
this works the first time the browser hits /cars, however, if I push the back on forward button in the browser to hit the url a second time without a page reload, the {{car}} is not being rendered. If the cars.html is put in the templateCache like this:
angular.module('app').run(function($templateCache) {
$templateCache.put('cars.html', '<div ng-repeat="car in cars">{{ car }}</div>');
});
the {{car}} binding is not rendered either.
I suspect this has something to do with Angular not unwrapping promises in templates anymore, but not totally sure. Does anyone know what I am doing wrong and how to write this code correctly?
Well, I saw some syntax errors in your code (maybe you didn't copy the code but typed it manually for SO not sure). Also you returned deferred instead of deferred.promise. What you trying to achieve works just fine:
Plnkr Example