communicate between angular controller and route controller - angularjs

index.html
<body>
<div data-form-modal >
<form>
<input type='text' name='test'/>
<input type='submit' value='submit' ng-click='submit()'/>
//this submit() function is in mainCtrl
</form>
</div>
</body>
this is my route:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainCtrl',
templateUrl: 'index.html'
})
.otherwise({
redirectTo: '/'
});
});
mainCtrl:
controller.mainCtrl = function(){
...
$scope.submit = function(){
alert(1)
}
}
form modal directive:
directive.formModal=function(){
return {
...
}
}
when I click the submit button, I try to call the submit() function in mainCtrl, but nothing heppend, I think its because the mainCtrl is a route controller and dosen't belong to any scope, and the formModal directive can't access the submit method.
I want the mainCtrl to handle the restful service and the formModal directive handle the form validation, but I dont know how to call method in mainCtrl from the formModal, and what is the relationship between the mainCtrl and the formModalCtrl?
edited:
I try to move the restful method to a service, and call the service method in formModal directive controller , it works fine, but I still need to access the mainCtrl in order to update the model so that the view can change accordingly.

What I've done is:
var app = angular.module('myApp', ['controllers'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
controller: 'mainCtrl',
templateUrl: 'index.html'
}).
otherwise({
redirectTo: '/'
});
}]);
var controllers = angular.module('controllers', []);
Then:
// separate file
controllers.controller('mainCtrl', ['$scope'
function ($scope) {
// do stuff with $scope
}
]);
You can probably do app.controller('mainCtrl' ... instead and save a controllers variable. I just happened to get this working on my site this way.
Also, make sure you have an ng-app of myApp enclosing an element with ng-view (for routing to work).

Related

Angular Modal Window not working for the life of me

I'm very new to Angular.js.
I've taken the necessary elements from this tutorial on modal windows within Angular.js: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
Isolated, I can get this code to work, but after porting it to my website, I just can't get it to work.
In Jason's code, he has a file called index.controller.js, and although I've ported this file to my own page, I don't believe it's firing. Here's index.controller.js:
(function () {
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller(ModalService) {
var vm = this;
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
}
})();
On my own page, I have all the controllers contained within app.js. Here's how it's laid out:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
})
...
});
You can see that, in the second .state, I'm attempting to call on the index.controller.js file for this particular partial. For some reason, though, the code under screeningsController (down below) is the code that's firing.
Further down in the same app.js file, I have my controllers:
...
app.controller('screeningsController', ['$scope', '$log', function($scope, $log){
$scope.popup = function() {
// assign a message to the $scope
$scope.message = 'Hello World!';
// use the $log service to output the message in a console
$log.log($scope.message);
};
}]);
...
Is there any way I can somehow integrate what's in the index.controller.js file into my screeningsController in the app.js? I've been trying to get a modal window working on my site for about a week now. Any help is much appreciated.
Start by creating a controller with identifier Home.IndexController. Based on the route configuration this will instantiate when you navigate to "/screenings". Call the popup() function attached to $scope of Home.IndexController via a directive us ng-click for testing. As you have specified controllerAs make sure to reference controller properties and methods prefixed with vm..
You do not need both index.controller.js and app.js both loaded. It looks everything you'd need is defined in app.js, so just make sure that is being loaded in your application. Eventually you'd want to separate these into different files and/or modules as necessary.
Try the following:
Configuration:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
});
...
});
Home.IndexController:
app.controller('Home.IndexController', ['$log', function($log){
var vm = this;
vm.message = '';
vm.popup = function() {
vm.message = 'foobar';
$log.log(vm.message);
}
}]);
Screenings Template:
<!-- Home.IndexController /screenings template -->
<div>
<button type="button" ng-click="vm.popup()"></button>
</div>
This also assumes you have ui-view specified somewhere in your main template like index.html or equivalent:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body ng-app="app">
<div ui-view></div>
<!-- Vendor and Custom scripts added here -->
</body>
</html>

The controller with the name 'complatedtabs' is not registered

my controller
(function() {
'use strict';
angular
.module('portfolio')
.controller('completedTabsController', completedTabsController);
function completedTabsController($scope){
$scope.go = function(){
alert("hi");
};
}
})();
my html
<button class="primary-btn add-offline pull-right" ng-click="completedTabsCtrl.openOfflineDealForm()">Add Offline Deal</button>
my module.js
$stateProvider
.state('dashboard.portfolio.complatedtabs', {
url: '/complatedtabs',
templateUrl: PORTFOLIO_URL + '/complatedtabs/complatedtabs.tpl.html',
controller: 'complatedtabs',
controllerAs: 'completedTabsCtrl'
});
But it showing this error
The controller with the name 'complatedtabs' is not registered.
How i will fix this??
Controller name should be from what you registered with controller method. Try like below.
$stateProvider
.state('dashboard.portfolio.complatedtabs', {
url: '/complatedtabs',
templateUrl: PORTFOLIO_URL + '/complatedtabs/complatedtabs.tpl.html',
controller: 'completedTabsController',
controllerAs: 'completedTabsCtrl'
});
If You are confused and wanted make sure by listing all the registered controllers. Use below code which will give you all the registered controllers and this is a test code.
// Test Code
var appModule = angular.module('myApp',[]);
angular.module('myApp').controller('MainCtrl', function($scope) {
$scope.controllers = appModule._invokeQueue.filter(function(el){
return el[0] === "$controllerProvider";
}).map(function(el){
return el[2]["0"];
});
});
angular.module('myApp').controller('TestCtrl', function(){});
angular.module('myApp').controller('TestCtrl2', function(){});
Controller name in the route declaration (complatedtabs) does not match the controller name in its definition (completedTabsController): you should have the same name in both, for instance just change the controller to:
.controller('complatedtabs', completedTabsController);
Please also note a possible typo: complAtedtabs

how to send the data of a ng-controller to another jsp page when click on send button?

Here i will add the product data from response of http for myctrl then when i click on checkout i have to bind all this information and send it to another jsp page in that page i have to get the response data.How can i achieve it by using angularjs. please help me out
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-repeat="x in names">
<div>Product Name : {{x.itemname}}</div>
<div>Qty : {{x.itemQty}}</div>
<div>Price : {{x.itemQty}}</div>
<div>Total : {{x.itemQty}}</div>
</div>
<div><button ng-click="checkOut()" >CheckOut</button></div>
</div>
<script>
angular.module("MyApp",[])
.controller("MyCtrl", ['$scope', '$http', function($scope, $http) {
$http.get('responseData.html').success(function(response) {
$scope.names= response;
});
}]);
</script>
Whenever you want to persist the any object/value on client side, I'd suggest you to don't redirect the user to other page.
Instead do create a SPA, add route based view to your application. For implementing such a powerful SAP you could use angular-route API designed by angular team OR you could also use ui.router which is developed by angular-ui team. Suppose you choose angular-route here then, show different view on different routes, you need to configure you route in angular config phase using $routeProvider & then load view and controller for partial view. In your case it would be confirmation submit page on click of button.
You could have one wrapper div on your ng-view directive and then give mainCtrl controller to it. That will act as a sharing component amongest your various views.
HTML
Controller
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1.html',
controller: 'CustomerDetailsController'
})
.when('/view2', {
templateUrl: 'view2.html',
controller: 'form2Ctrl'
})
.otherwise({
redirectTo: '/view1'
});
});
app.controller('mainCtrl', function($scope) {
$scope.form = {}; //this is global and thats why it can be available on any view
});
app.controller('CustomerDetailsController', function($scope,$location) {
$scope.submit = function(){
if($scope.form1.$valid)
$location.path('/view2');
};
});
app.controller('form2Ctrl', function($scope,$location) {
//this controller contain the data which will you get from
});
Preferable approach for sharing a data would be using singleton service/factory in your application.
HTML
<div class="forms">
<ng-view></ng-view>
</div>
app.service('sharedData', function() {
var sharedData = this;
sharedData.myData = {};
});
app.controller('CustomerDetailsController', function($scope,$location, sharedData) {
$scope.submit = function(){
sharedData.myData.formData = $scope.form1Data; //form1Data will have form1Data
if($scope.form1.$valid)
$location.path('/view2');
};
});
app.controller('form2Ctrl', function($scope,$location, sharedData) {
console.log(sharedData); //this will have the data shared from the CustomerDetailsController
});
For more info Refer this SO Question, Thanks.

how does todo mvc example for angularjs do without ng-controller?

Every example I've looked at has made use of the ng-controller directive to get things working.
The Todo MVC example at https://github.com/tastejs/todomvc/tree/gh-pages/examples/angularjs creates a 'TodoCtrl' controller. But in the corresponding index.html, there is no use of the ng-controller directive.
How is this possible? and why did they choose to do it this way?
It uses the ngRoute provider.
angular.module('todomvc', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
var routeConfig = {
controller: 'TodoCtrl',//add controller to view
templateUrl: 'todomvc-index.html',
resolve: {
store: function (todoStorage) {
// Get the correct module (API or localStorage).
return todoStorage.then(function (module) {
module.get(); // Fetch the todo records in the background.
return module;
});
}
}
};
$routeProvider
.when('/', routeConfig)
.when('/:status', routeConfig)
.otherwise({
redirectTo: '/'
});
});

Angular routes and views and controllers

I am trying to make a very simple app with routes and views, that displays a test text changing into "click" when a button is clicked.
I have an index.html file with an ng-view thats calls properly a test.html view. This view is supposed to use a testCtrl.js with a simple model.
But when it loads, the view seems to be called, but there is a problem with the scope, or the controller. When I click on a button the word test is supposed to become "click" but nothing happens.
here is the index.html
<body ng-app="simtoolbelt">
<div ng-view></div>
<script src="js/modules/angular-route.min.js"></script>
<script src="js/controllers/testCtrl.js"></script>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
here is the app.js handling the routes and views:
var simtoolbelt = angular.module('simtoolbelt', ['ngRoute']);
simtoolbelt.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/test', {
templateUrl: 'views/test.html',
controller: 'testCtrl'
}).
otherwise({
redirectTo: '/test'
});
}]);
The test controller:
simtoolbelt.controller('testCtrl', ['$scope', function($scope){
$scope.test = "test";
$scope.change = function($scope){
$scope.test = "Click";
};
}]);
And finally the test view:
<div ng-controller="testCtrl">
<h1 ng-model="test">Le {{test}} fonctionne</h1>
<button ng-click="change()">Click</button>
</div>
All of that is in a localhost, and I really have no clue of what it is I am mising... Thanks lot guys for any help you can give me !
Your function "change" takes the argument "$scope". In ng-click you call a method without arguments.
Remove the parameter from your change method:
$scope.change = function(){
$scope.test = "Click";
};
Furthermore, there is no need for the ng-model attribute in your h1 tag.
Try to change controller definition in your routing to "only controller name" like
simtoolbelt.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/test', {
templateUrl: 'views/test.html',
controller: 'testCtrl'
}).
otherwise({
redirectTo: '/test'
});
}]);
I have not test it yet but it should work.

Resources