how to change template in controller angularjs - html

I am trying to generate the template for the state in the dynamically with the controller as follows:
app.config( function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl:'homeView.html',
controller: 'homeController'
})
.state('review', {
url: '/pendingPaymentReview',
template: null,
templateProvider: function($stateParams){
return $stateParams.template;
},
controller: 'reviewController'
});
And then define the controllers as:
app.controller('reviewController', function ($scope, tempData, $stateParams) {
var template = tempData.getTemptlate();
$stateParams.template = template;
alert($stateParams.template);
tempData is a service that retrieves the page fragment from the server using $http.
My question is how do modify access and modify the template parameter of the review state? I have tried using $stateParams but got no display page. Any help will be more than appreciated.

Related

to get the parameter from the url in angularjs

I have a page add recommendation and same page for the edit recommendation when I click on the add recommendation the recommendation Id is null in the URL, but when I go the page by clicking the recommendation link it will show that respective Id for the recommendation, in URL it is showing but how to get that Id from the URL to use it.
My code is:
.state('Admin.AddRecommendation',{
url: "/AddRecommendation/:recoId",
templateUrl: "views/AddRecommendation.html",
params: {recoId:null},
})
controller.js:
$scope.addRecommendation = function(){
var id = $routeParams.recoId;
console.log(id);
So where I am doing it wrong.
Thanks
As you are defining recoId in the url, you don't need params: {recoId:null},
.state('Admin.AddRecommendation',{
url: "/AddRecommendation/:recoId",
templateUrl: "views/AddRecommendation.html"
})
You can access the params in the controller by injecting $stateParams
app.controller('MyController', ['$scope', '$state', '$stateParams', function($scope, $state, $stateParams) {
$scope.addRecommendation = function(){
var id = $stateParams.recoId;
console.log(id);
}
}]);
If you are using components, $stateParams is deprecated in favor of $transition$
However, it is not as straightforward to implement that: https://github.com/angular-ui/ui-router/issues/3110#issuecomment-271101827
Basically, you can use it as
.component('foo', {
bindings: { $transition$: '<' },
controller: MyController,
controllerAs: 'vm'
});
app.controller('MyController', ['$scope', '$state', function($scope, $state) {
var vm = this;
$scope.addRecommendation = function(){
var id = vm.$transition$.params().recoId;
console.log(id);
}
}]);
To get the query params from the URL when using ui-router, you can use
In your controller.js:
$state.params
This will give you all the params in the URL. To get specific param:
$state.params[<your-query-param>]
EDIT: In your question, instead of $routeParams, use $state

Table is blank forever - loading page with ngRoute

I am using angular routers
app.config(function($routeProvider) {
$routeProvider
.when('/comment/list', {
templateUrl: 'commentList.htm',
controller: 'mainController'
})
});
<td ng-show="btnUADetails" ng-click="loadPage('commentList', x.userName);">
<a class="detailButton" href="#/comment/list"></a>
</td>
and here is my angular function
$scope.loadPage = function(pageId, id) {
if (pageId == "commentList") {
$scope.getServerData($scope.generateUrl(pageId, 'json', id)).then(function(result) {
$scope.serverComment = result;
});
} else {
//do something
}
}
Before $HTTP returns response html page loads and i am getting clean data in html table . Can i load this page after my functions returns result ? Or load html file first and load it again when functions returns result ?
When the router changes routes, it destroys the $scope of the current view and creates a new $scope with a new instance of the controller.
Include any information the new view needs as query parameters in the new URL.
Change the link to include a parameter:
<td ng-show="btnUADetails" ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶l̶o̶a̶d̶P̶a̶g̶e̶(̶'̶c̶o̶m̶m̶e̶n̶t̶L̶i̶s̶t̶'̶,̶ ̶x̶.̶u̶s̶e̶r̶N̶a̶m̶e̶)̶;̶"̶ >
<a class="detailButton" href="#/comment/list?id={{x.userName}}"></a>
</td>
Use the parameter in the controller:
app.controller("mainController", function($scope, $route) {
this.$onInit = function() {
if ($route.current.templateUrl == 'commentList.htm') {
var pageId = 'comment';
var id = $route.current.params.id;
$scope.getServerData($scope.generateUrl(pageId, 'json', id))
.then(function(result) {
$scope.serverComment = result;
});
};
};
});
In the above example, the new instance of the controller uses the current params of the router to load the necessary data.

Populating a BackboneJS model with response from an API endpoint

I'm new to BackboneJS but I'm doing my best to learn it. I'm more familiar with AngularJS so I have some confusion in BackboneJS but would definitely want to become an expert BackboneJS developer too.
Back at my previous job, I was the frontend dev and I would work with the Java dev guy. We would have a meeting about how the JSON response would look like. Basically, I'll make a REST call(either with Restangular or $http) to one of their endpoints and I'll get a response. The JSON response will be assigned to a scope variable such as $scope.bookCollection. In my template, I'll just use ng-repeat to display it.
Now with BackboneJS, I'd like to do it properly. I read today that a BackboneJS Model is a container. What I'd like to happen is that after making a fetch(), I want the JSON response to be put in the Model that I defined. How is that done?
I found an example jsfiddle but I think it's a very bad example. I can't find something that is helpful right now, something with a good fetched data.
require.config({
paths: {
jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
underscore: 'http://underscorejs.org/underscore',
backbone: 'http://backbonejs.org/backbone-min'
},
shim: {
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
underscore: {
exports: "_"
}
}
});
require([
'jquery',
'underscore',
'backbone'], function ($, _, Backbone) {
var UserModel = Backbone.Model.extend({
urlRoot: '/echo/json/',
defaults: {
name: '',
email: ''
}
});
var userDetails = {
name: 'Nelio',
email: 'nelio#angelfire.com'
};
var user = new UserModel(userDetails);
user.fetch({
success: function (user) {
console.log(user.toJSON());
}
});
});
Here is the jsfiddle:
http://jsfiddle.net/20qbco46/
I want the JSON response to be put in the Model that I defined. How is
that done?
If you are trying to render the data from you model, you will use a view for this:
First, create a view to render your data:
// Create a new view class which will render you model
var BookView = Backbone.View.extend({
// Use underscores templating
template: _.template('<strong><%= title %></strong> - <%= author %>'),
initialize: function() {
// Render the view on initialization
this.render();
// Update the view when the model is changed
this.listenTo(this.model, "change", this.render);
},
render: function() {
// Render your model data using your template
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
See also: template and toJSON as well as $el
Next, create a Model:
// Create a model class
var Book = Backbone.Model.extend({
urlRoot: '/echo/json/',
defaults: {
title : '',
author: ''
},
});
Your model will hold the data fetched from the url / urlRoot
You can use set if you are trying to add new attributes to your model.
You can use get to grab attributes from your model.
See also - save and destroy.
Then, instantiate your model:
// Some dummy data
var instance = {
title: 'learn Backbone JS',
author: 'Bobby Longsocks',
};
// Instansite your model
var model = new Book(instance);
And finally, fetch your model data and create a new instance of you view:
// Fetch your model
model.fetch({
success: function(book) {
// Instansite your view, passing in your model
var view = new BookView({model: book, el: $('body')});
}
});
Here is an Example you can fiddle with.
And some further reading: Annotated Source

How to use a angularjs route to call a javascript function

I'm trying to use the routing of angularjs to call a javascript function if a certain url is used.
The following code is not providing the expected result:
var app = angular.module('myApp', []);
app.config(function($routeProvider) {
$routeProvider.when('/link1', {
controller: 'PageController'
})
.when('/link2', {
controller: 'PageController'
})
.otherwise({
controller: 'PageController'
});
});
app.controller('PageController', function($scope, $routeParams) {
alert('1');
});
The alert(1); is not called if one of these URLs are requested...
Maybe someone knows how to solve this ?
Controller is not called until you specify template or templateUrl option in $routeProvider configuration. If there is no template needed, you could specify one-space char (but not empty string). Like so
$routeProvider.when('/link1', {
controller: 'PageController',
template: ' '
})
There is no way to associate the routing with a specific action in the controller. The routing in the AngularJS is not like the routing in other web frameworks to route to specific action of request. Instead, the routing in the AngularJS is primarily relating to handle the page flow and the controller defines the scope of the page.
However, if you put the alert in the controller like that, it should be triggered when the page is loaded. You need to check whether the URL you used is correct or not. To test, you can simply put $location.url('/link1') in your code.
If your controller is being used on a particular route, then you can call that function inside the controller. It will get executed once the route changes and your controller is called.
In this http://plnkr.co/edit/qUZ5Q7nKCRAS8dFvjRIg when you click on link1 it displays alert.
I can't quite catch why your code doesn't work as expected, but I created a similar app setup and it works:
var app = angular.module('myApp',[]).
config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/', {
controller: 'PageController',
template: '<br><br>this is page #/<br> {{data}}',
}).
when('/link1', {
controller: 'SpecificPageController',
template: '<br><br>this is page #/link1<br> {{data}}'
}).
when('/link2', {
controller: 'PageController',
template: '<br><br>this is page #/link2<br> {{data}}'
}).
otherwise({redirectTo:'/'});
}]).
controller('PageController', function($scope, $routeParams) {
$scope.data = 'hello world';
}).
controller('SpecificPageController', function($scope, $routeParams) {
$scope.data = 'hello specific';
alert(1);
});
Whenever SpecificPageController is assigned to a route, and that route opened, the alert function gets executed.

relating service and controller AngularJS Error: Unknown provider: myservicesProvider <- myservices

I am getting this error and I tried different methods, but still I have not found any solution.
This is my code:
app.js
angular.module('myApp', [ 'myApp.services','myApp.filters', 'myApp.directives',
'myApp.controllers']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/Receive', {templateUrl: 'partials/partial1.html', controller: 'ReceiveCtrl'});
$routeProvider.when('/Pending', {templateUrl: 'partials/partial2.html', controller: 'PendingCtrl'});
$routeProvider.when('/ResumePending', {templateUrl: 'partials/partial3.html', controller: 'PendingCtrl'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
services.js
angular.module('myApp.services',[])
.service('myservice',function($resource)
{
var pendings = $resource('myUrl2', {methode: 'GET', isArray:true});
var items;
var myPo='rawad al bo3bo3';
var quantity;
var barcode;
return{
getItems: function(){
items =$resource('myUrl', {methode: 'GET', isArray:true});
return items ;
},
setQty: function(qty){
quantity=qty;
},
deletePO : function(id){
},
suspend:function(id){
//URL needed
},
}).
value('version', '0.1');
And this is my controllers:
angular.module('myApp.controllers', []).controller('ReceiveCtrl', ['$scope','myservice', function ($scope,myservice) {
$scope.po='rawad';
alert ('WoW!! It is '+myservice.getPO);
$scope.quantity='';
$scope.barcode='';
$scope.addProduct= function(){
myservice.setQty($scope.quantity);
myservice.setBc($scope.barcode);
myservice.addToPliste;
};
}]);
In the controller I can't access the variable coming from my services... so the alert message won't work and I get this error
Error: Unknown provider: myservicesProvider <- myservices
Service declaration:
angular.module('myApp.services',[]).
service('myservice',function($resource)
Service injection in controller:
angular.module('myApp.controllers', []).
controller('ReceiveCtrl', ['$scope','myservices', ...
The service is named myservice, but you use myservices when injecting it.
In your service.js you have named your service as "service" and in your controller you are calling it as "services". That is the error. Change services in controller to service
Try this too;
In your app.js
angular.module('myApp', [ 'myApp.services','myApp.filters', 'myApp.directives',
'myApp.controllers', 'ngResource']).
And in your index.html include the angular-resource.js file. This might solve your issue.