how to call a controller in ionic? - angularjs

In my ionic blank app, i have two html file index.html and category.html.
i write the controller for index.html in app.js like
.controller('AppCtrl',function($scope){
$scope.menu = function() {
console.log('yesytest');
window.location = "category.html";
};
})
this is working fine and after reaching the category page i create another controller in app.js
controller('categoryCtrl',function($scope){
console.log('ffffffffff');
$scope.beauty = function() {
console.log('yesytest');
window.location = "categorydetails.html";
};
});
i add a ng-click function on a button inside category.html but when i click on that button it is not calling the controller?

You can define your controller either on :
- defining it on your ui router state
.state('camera',{
url:"/camera",
cache: false,
controller:"CameraCtrl",
templateUrl:'app/views/loading/index.html'
})
Or by defining it into tour template category.html
<div ng-controller="categoryCtrl"> .... </div>
This is standard AngularJS feature, nothing special with ionic

If you use this :
.state('category',{
url:"/category",
controller:"categoryCtrl",
templateUrl:'templates/category.html'
})
You can use ui-sref="stateId" to do redirection
Example:
<a ui-sref="category"></a>

..Hi Kindly route your controller just define them..This might help.. --> http://learn.ionicframework.com/formulas/navigation-and-routing-part-1/ ^_^
//app.js
.state('category',{
url:"/category",
controller:"categoryCtrl",
templateUrl:'templates/category.html'
})
//index.html
<a ng-href="#/category"></a>

Related

Page navigation using routing

I am trying to navigate to a new jsp page on click of a link . I am using routing for this .
home.jsp
I am having below div outside the ng-view directive .If I am putting this inside ng-view ,Page is not working properly .I dont know if it should be inside or outside .
<div>
<h4> <a href ="#/Mix.web" data-ng-click="getMixData()" target="_self">Overall Mix
</a></h4>
</div>
Mix.jsp
I have not put it inside ng-view .Again If I am enclosing it inside ng-view ,the page is not loading .
Controller js
var app = angular.module('myApp', []);
app.config(function($routeProvider) {
$routeProvider
.when('/home.web', {
templateUrl : 'Views/Home.jsp',
controller : 'MyController'
})
.when('/Mix.web', {
templateUrl : 'Views/Mix.jsp',
controller : 'MyController'
});
});
Few things I have debugged .
Onclick of the link , controller function is getting called and subsequent java spring controller is sending data successfully as well .
I am not able to figure out if this is the correct way to implement routing . What am I doing wrong here .

ng-include and ngRoute: how to make them work together? (i.e. route to a view wihin a ng-include)

[EDITED] My app has the following structure:
index.html
<body ng-app = "myApp" ng-controller ="mainController">
<ng-view></ng-view>
</body>
mainView.html (loaded into ng-view through routeProvider in app.js)
<div ng-include src="subview1">
<div ng-include src="subview2">
subview1 and subview2 are set within mainController (mainView's controller) as scope variables:
$scope.subview1= "templates/subview1.html";
$scope.subview2= "templates/subview2.html";
controller1 and controller2 are subview1 and subview2's controllers.
subview1.html (loaded in first div of mainView)
<div ng-controller="controller1">
<button ng-click="loadNewView()"></button>
</div>
controller1.js
.controller('controller1', function($scope){
$scope.loadNewView = function(){
$scope.$parent.subview1 = "templates/view3.html";
}
}
scope.loadNewView should load a different view (and relative controller) within the div with src="subview1" in mainView.html). Basically it's about refreshing the view itself by raplacing it with another view (and related controller).
I use $parent to update the view in subview1's parent view (i.e. mainView).
however nothing happens and if I try to use $scope.$apply() I get error (digest already in progress).
Any clue?
you can try something like this...
In your stateProvider or in your routeProvider if you using.
var mod = angular.module('example.states', ['ui.router']);
mod.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('exampleState', {
url: '/main',
templateUrl: 'mainView.html',
controller: mainController
});
}
]);
return mod;
So here you have associated your parent controller(let's say the mainController which will be the parent of all others) with its template mainView.html.
Then in your mainView.html,Load all the subview templates.
<div ng-repeat="template in templates">
<ng-include src="template.url"></ng-include>
</div>
templates is an array in your mainController which has the url or path of all your subtemplates.When you use ng-include inside the main template then all subTemplates will automaticlly become the child of the mainTemplate and its Controllers too.In a way it will inherit from the parent Controller.
So suppose if subView1.html is one of the template url you had given in ng-include.Then it will look like
<div ng-controller="subView1Controller">
//Here your code
</div>
And subview2 as
<div ng-controller="subView2Controller">
//Here your code
</div>
This way you will have multiple views on the same page with one url and different controllers with its associated templates and each will inherit from the parent controller which is mainController here.
There, might be better approach than this.
This is what i had used in my project,and its simple to keep your code simple manage.
Okay,so using routeProvider,you can use it like this
var app = angular.module("app",[]);
app.config(function($routeProvider){
$routeProvider
.when('/main',{
templateUrl:"mainView.html",
controller:mainController
})
});
app.controller("mainController",function($scope){
});
app.controller("subView1Controller",function($scope){
});
app.controller("subView1Controller",function($scope){
});
Then in your mainView.html,Load all the subview templates.
<ng-include src="yoursubtemplate1path"></ng-include>
<ng-include src="yoursubtemplate2path"></ng-include>
And then in yoursubtemplate1 use
<div ng-controller="subView1Controller">
//Here your code
</div>
Same for the other templates.
You can set the template src of the subtemplates from your mainController.
app.controller("mainController",function($scope){
$scope.templatesrc="/app/template1.html";
});
And then use it in your template,where you are using ng-include directive.
<ng-include src="templatesrc"></ng-include>
Its better to store template url's in an array and use ng-repeat directive like i had stated before,if you are loading more templates.
And if you want to show the div on some button click lets say in parent controller then use ng-if in the sub-view main and make it true on button click.
This answer is regarding your updated question.
The solution which you had used before,will load all temlplate and once in ng-include and its associated controller making the mainController as parent.
But if you want to load a different view with its newController then you can try something like this.
Just add one more route and call on your event click,but remember this newView's Controller will have no parent-child relation with the mainView's controller.
var app = angular.module("app",[]);
app.config(function($routeProvider){
$routeProvider
.when('/main',{
templateUrl:"mainView.html",
controller:mainController
})
.when('/anyName',{
templateUrl:"templates/view3.html",
controller:temp3Controller
})
});
And in your controller1.js
.controller('controller1', function($scope){
$scope.loadNewView = function(){
$location.path('/anyName');
}
}
Inject location service in controller1.
I finally found the solution.
The tricks is using
$scope.$parent.$parent.subview1 = "templates/view3.html";
instead of
$scope.$parent.subview1 = "templates/view3.html";
since, basically:
ng-include is the child of mainView
subview1 is the child of ng-include

angular ionic, how to reload controller on link in the markup

I want to reload the controller I'm linking to in a menu in an ionic angular app. How do I declare the link in the markup so that it refreshes the destination route every time the link is clicked?
I saw this bit of code
$state.go($state.current, {}, {reload: true});
Which I suppose I can wrap in a controller method but I would prefer to do it in the markup if possible.
Wrap it in a function in your controller:
$scope.reload = function () {
$state.go($state.current, {}, { reload: true });
}
Then use it in your view:
<button ng-click="reload()">Reload</button>

AngularJS not updating binding when using routes

I am trying to get a small angularJS app running. The app should receive asynchronous messages via STOMP / Websockets. If a message via the web socket arrives, the angular app is supposed to display a changed value in the UI. In general angular's data binding works as expected, but if the scope is updated within the callback function on_message() nothing happens in the UI. I have read various post on similar topics and tried the suggested solutions like using $apply within the callback function, but without success.
In the debugger I can see that the $scope.SoC gets assigned the correct value, but the UI remains unchanged.
If the function on_message(m) is called directly - just for testing - and not from socket-client, the UI gets updated correctly.
This is the abbreviated structure of the controller code
App.controller('showCaseDataCtrl', function($scope){
var mySoC = 0.7;
$scope.status = {statusMessage: "No Message", SoC: 0.77, power: 5.4, numDevices: 89};
function on_message(m) {
mySoC ++;
$scope.$apply(function() {$scope.status.SoC = mySoC;});
console.log(mySoC);
}
});
This is the HTML
<html ng-app="App">
...
<div class="col-md-4" >
<h1> <span ng-bind="status.SoC" /> SoC</h1>
<p>Charge Status</p>
</div>
...
</html>
Any suggestions what else to try are appreciated.
Update:
The problem has to to with mg-route and a separate view in the main HTML
in the main HTML I am using a statement like
<!-- views selected by the route will be injected here -->
<div ng-view ="" </div>
and the route provider looks like
App.config(function($routeProvider){
$routeProvider
.when('/',
{
controller: 'showCaseDataCtrl',
templateUrl: 'partials/Overview.html'
})
.when('/test',
{
controller: 'showCaseDataCtrl',
templateUrl: 'partials/Overview.html'
})
.otherwise({redirectTo: '/'});
});
Removing the route provider and putting all HTML directly in the main HTML with
<div ng-controller="showCaseDataCtrl" class="col-md-4" >
<h1> <span ng-bind="status.SoC" /> SoC</h1>
<p>Charge Status</p>
</div>
solved the problem.
--- But I have no clue why ---
Any explanation appreciated
The reason the $scope is not updating is because the callback is happening outside of Angular's $digest() cycle. Try wrapping it in $scope.$apply.
function on_message(m) {
// console.log('Received:' + m);
// var MyJSON = $.parseJSON(m.body);
mySoC ++;
$scope.$apply(function() {
$scope.SoC = mySoC;
});
console.log(mySoC);
}
});
Seems like you had it commented out, but that should work.

AngularJs: Reload page

<a ng-href="#" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
I want to reload the page. How can I do this?
You can use the reload method of the $route service. Inject $route in your controller and then create a method reloadRoute on your $scope.
$scope.reloadRoute = function() {
$route.reload();
}
Then you can use it on the link like this:
<a ng-click="reloadRoute()" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
This method will cause the current route to reload. If you however want to perform a full refresh, you could inject $window and use that:
$scope.reloadRoute = function() {
$window.location.reload();
}
**Later edit (ui-router):**
As mentioned by JamesEddyEdwards and Dunc in their answers, if you are using angular-ui/ui-router you can use the following method to reload the current state / route. Just inject $state instead of $route and then you have:
$scope.reloadRoute = function() {
$state.reload();
};
window object is made available through $window service for easier testing and mocking, you can go with something like:
$scope.reloadPage = function(){$window.location.reload();}
And :
<a ng-click="reloadPage" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
As a side note, i don't think $route.reload() actually reloads the page, but only the route.
location.reload();
Does the trick.
<a ng-click="reload()">
$scope.reload = function()
{
location.reload();
}
No need for routes or anything just plain old js
Similar to Alexandrin's answer, but using $state rather than $route:
(From JimTheDev's SO answer here.)
$scope.reloadState = function() {
$state.go($state.current, {}, {reload: true});
}
<a ng-click="reloadState()" ...
If using Angulars more advanced ui-router which I'd definitely recommend then you can now simply use:
$state.reload();
Which is essentially doing the same as Dunc's answer.
My solution to avoid the infinite loop was to create another state which have made the redirection:
$stateProvider.state('app.admin.main', {
url: '/admin/main',
authenticate: 'admin',
controller: ($state, $window) => {
$state.go('app.admin.overview').then(() => {
$window.location.reload();
});
}
});
Angular 2+
I found this while searching for Angular 2+, so here is the way:
$window.location.reload();
This can be done by calling the reload() method in JavaScript.
location.reload();
It's easy enough to just use $route.reload() (don't forget to inject $route into your controller), but from your example you could just use "href" instead of "ng-href":
<a href="" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
You only need to use ng-href to protect the user from invalid links caused by them clicking before Angular has replaced the contents of the {{ }} tags.
On Angular 1.5 - after trying some of the above solutions wanting to reload only the data with no full page refresh, I had problems with loading the data properly. I noticed though, that when I go to another route and then I return back to the current, everything works fine, but when I want to only reload the current route using $route.reload(), then some of the code is not executed properly. Then I tried to redirect to the current route in the following way:
$scope.someFuncName = function () {
//go to another route
$location.path('/another-route');
};
and in the module config, add another when:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/first-page', {
templateUrl: '/first-template',
controller: 'SomeCtrl'
}).when('/another-route', {//this is the new "when"
redirectTo: '/first-page'
});
}])
and it works just fine for me. It does not refresh the whole page, but only causes the current controller and template to reload. I know it's a bit hacky, but that was the only solution I found.
<a title="Pending Employee Approvals" href="" ng-click="viewPendingApprovals(1)">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="button_badge">{{pendingEmployeeApprovalCount}}</span>
</a>
and in the controller
$scope.viewPendingApprovals = function(type) {
if (window.location.hash.substring(window.location.hash.lastIndexOf('/') + 1, window.location.hash.length) == type) {
location.reload();
} else {
$state.go("home.pendingApproval", { id: sessionStorage.typeToLoad });
}
};
and in the route file
.state('home.pendingApproval', {
url: '/pendingApproval/:id',
templateUrl: 'app/components/approvals/pendingApprovalList.html',
controller: 'pendingApprovalListController'
})
So, If the id passed in the url is same as what is coming from the function called by clicking the anchor, then simply reload, else folow the requested route.
Please help me improve this answer, if this is helps. Any, suggestions are welcome.
This can be done by calling the reload() method of the window object in plain JavaScript
window.location.reload();
I would suggest to refer the page. Official suggestion
https://docs.angularjs.org/guide/$location

Resources