This might be me just missing something or getting the wrong end of the stick on the tutorial, so bear with me.
I have my app....
var shepApp = angular.module('shepApp', [
'ngRoute',
'ui-notification',
'shepControllers',
'shepFilters',
'shepServices'
]);
shepApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/galaxies', {
templateUrl: "partials/galaxies.html",
controller: 'GalaxyListCtrl'
}).
}]);
And my controllers go something like this....
var shepControllers = angular.module('shepControllers', []);
shepControllers.controller('GalaxyListCtrl', ['$scope', '$location', 'Notification', 'Galaxy', function($scope, $location, Notification, Galaxy) {
$scope.galaxys = Galaxy.query();
$scope.blah = function(){
alert(123);
}
}]);
shepControllers.controller('GalaxyDetailCtrl', ['$scope', '$routeParams', '$location', 'Notification', 'Galaxy', function($scope, $routeParams, $location, Notification, Galaxy) {
$scope.galaxy = Galaxy.get({slug: $routeParams.slug});
}]);
My galaxies.html partial contains the following HTML using ng-click.
<button ng-click="blah"></button>
My thinking was that that blah function for the click event would be exposed when my route is /galaxies and the controller in use is GalaxyListCtrl - but the alert is never fired at all.
I think I am missing something in the way this all fits together.
Calling a function without arguments is done using the name of the function followed by parentheses:
ng-click="blah()"
Related
I'm new using Angular with MVC Web Api but using VB instead of C#. I'm trying to make an SPA web site and I have some week trying to solve this problem.
In my app.js I defined the routing to my views and the controllers I'm going to use in them
var goMessage = angular.module('goMessage', ['ngRoute', 'goMessage.controllers', 'goMessage.services', 'goMessage.directives']);
angular.module('goMessage.controllers', []);
angular.module('goMessage.services', []);
angular.module('goMessage.directives', []);
goMessage.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
//Vista Login
$routeProvider.when('/login/inicio', {
controller: 'loginController',
controllerAs: 'lgCtrl',
templateUrl: 'Home/Login'
});
//Vista Usuarios
$routeProvider.when('/usuarios/lista', {
controller: 'usuariosController',
controllerAs: 'usCtrl',
templateUrl: 'Home/Usuarios'
});
$routeProvider.when('/dashboard/inicio', {
controller: 'dashboardController',
controllerAs: 'dashCtrl',
templateUrl: 'Home/Dashboard'
});
$locationProvider.html5Mode(true);
}]);
The usuariosController.js controller is working very well, its code is:
angular.module('goMessage.controllers')
.controller("usuariosController", ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
//Ordenamiento por default
this.ordenarPorColumna = 'UsuarioID';
this.reverse = false;
// More code...
}
]);
And the loginController.js controller code is:
angular.module('goMessage.controllers')
.controller('loginController', ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
this.myData = "Data$$$";
}
]);
In the Login.vbhtml view I'm following the same pattern as the Usuarios.vbhtml view. I define my ng-app in the _layout.vbhtml and I don't define any controller inside any view.
The error I'm unable to solve is this:
Error Image
Look at the AngularJs Expression
As you can see, I've defined both controller using the same way but the only one that works is the usuarios one and any other controller I add doesn't work.
Here I show you the scripts loading order:
Scripts Loading Order
I'm using my local IIS and working in VS2012.
The angular JS version is 1.6.
To register the logic modules as controller, filter and etc..., you need to add this code in your app.config
var app = angular.module("App", []);
var config = function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
//your codes
}
config.$inject = ["$controllerProvider", "$compileProvider", "$filterProvider", "$provide"];
app.config(config);
Why this happen?
sometimes we don't need to add all of controllers in our main index which has ng-view or ui-view for that we should put our controller as lazyload to the app.config as you do this in your config, because of that the main app for get the controllers need to register controllers and other modules.
This issue might happen due to asynchronous loading of scripts. The script order might also be an issue. You can add a console.log at the beginning of loginController to check whether the component is loaded correctly.
edit: I'm using bootstrap, I think bootstrap tab is causing the
problem
View does not get updated after $scope variable update.
$scope.codeData
if i console the $scope.codeData, i can see the data, but does not render in view.
I have to click twice to get the view render correctly.
is there anything wrong with my code??
Thank you.
config
angular.module('SPAroutes', ['ngRoute', 'SPAcontrollers', 'SPAdirectives'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'templates/views/admin.html',
controller: 'adminCtrl',
controllerAs: 'admin'
})
$locationProvider.html5Mode(true).hashPrefix('!');
}]);
Controller.js
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
$scope.codeData = res.data;
console.log($scope.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
admin.html
{{codeData}}
You are mixing up controllerAs with scope as phil mentioned in his comment on question. Instead of using scope here store values insidethis reference something like this.
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
var admin = this;
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
admin.codeData = res.data;
console.log(admin.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
and inside the view: admin.html
{{admin.codeData}}
here is working plunk for your refernce
I'm trying to pass an object to the modal controller with resolve but it doesn't appear to pass correctly. I can console.log the object fine right before I pass it, but trying to log it in the modal controller just shows it is undefined. I've looked at other related questions but I can't see what I'm doing differently from the answers they've been given. Here's my controllers:
app.controller('BlogController', ['$scope', '$http', '$modal', function($scope, $http, $modal){
$scope.blogEntry = {}; // Place holder for data (blog entry)
$scope.editBlogEntry = function(blogEntry) {
$scope.blogEntry = blogEntry;
$scope.editModal = $modal.open({
templateUrl: '/resources/partials/editBlogModal.html',
controller: 'EditBlogController',
size: 'lg',
resolve: {
blogEntry: function() {
console.log($scope.blogEntry); //this shows the object
return $scope.blogEntry;
}
}
});
};
}]);
app.controller('EditBlogController', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance, blogEntry){
$scope.blogEntry = blogEntry;
console.log($scope.blogEntry); //undefined
}])
Can anyone see what I'm missing? Really appreciate the help!
You forgot to add blogEntry as the last string in the array passed to the modal controller.
app.controller('EditBlogController', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance, blogEntry)
HERE ^
Do yourself a favor, and use ng-annotate, which will remove the need for this ugly array syntax, and thus avoid those kinds of bugs.
I would like to work out how to convert this:
app.controller('AnswersCtrl', ['$scope', '$http', '$log', '$ionicModal', '$state', 'SuspectService',
function($scope, $http, $log, $ionicModal, $state, SuspectService) {
$scope.suspects = [];
SuspectService.getSuspects().then(function(data){
$scope.suspects = data;
});
$scope.goToClues = function(){
$state.go('clues')
};
}]);
into something that looks like this:
app.controller('AnswersCtrl', ['$http', '$log', '$ionicModal', '$state', 'SuspectService',
function($http, $log, $ionicModal, $state, SuspectService) {
var self = this;
self.suspects = [];
SuspectService.getSuspects().then(function(data){
self.suspects = data;
});
self.goToClues = function(){
$state.go('clues')
};
}]);
The code which utilises $scope works but the code which utilises this (self) doesn't.
I have tried a couple of variations and haven't been able to get it to work.
It looks like you are almost there in order for this syntax to work in your controllers you also need to change the markup where you define the controller to look like this:
<div ng-controller="AnswersCtrl as vm">
{{ vm.suspects[0].name}}
</div>
You can see a working example without the extra services you have defined in you example here: http://jsbin.com/zevaluside/3/edit
You will also require Angular 1.2 or higher for this to work as well.
I've two routes with resolve. Goes like this:
.when('/foos', {
templateUrl: 'views/foos.html',
controller: 'FoosCtrl',
resolve: {
foo_list: ['$q', '$route', '$timeout', '$location', 'Foos', function($q, $route, $timeout, $location, Foos) {
// postpone the execution
var deferred_foo = $q.defer()
Foos.getFoos({token:session_uid}, successCb)
function successCb(list) {
if(list['status'] === 200) {
deferred_foo.resolve(list)
}
else {
alert('Crashcrashcrash')
deferred_foo.reject("Something just wasn't right")
//$location.path('maintenance')
}
}
return deferred_foo.promise
}]
}
})
.when('/r/:type/:bar_id', {
templateUrl: 'views/bar.html',
controller: 'BarsCtrl',
resolve: {
bar: ['$q', '$route', '$timeout', '$location', 'Bars', function($q, $route, $timeout, $location, Bars) {
// postpone the execution
var deferred = $q.defer()
Bars.getBar({type: bar_type}, successCb)
function successCb(result) {
if(result['status'] === 200) {
deferred.resolve(result)
}
else {
alert('Crashcrashcrash')
deferred.reject("Something just wasn't right")
$location.path('foos')
}
return deferred.promise
}]
}
})
Then I've two controllers working like this:
App.controller('FoosCtrl', ['$scope', '$location', 'Foos', 'foo_list', function($scope, $location, Foos, foo_list) {...}
App.controller('BarsCtrl', ['$scope', '$routeParams', '$location', 'Bars', 'bar', 'sharedService', function($scope, $routeParams, $location, Bars, bar, sharedService) {...}
Could somebody explain why Bar works but Foo gives me Error: Unknown provider: foo_listProvider <- foo_list? I've tried replacing foo_list with different name in case camelCasing did something but didn't help.
So, this question was surprisingly similar to my own which I just figured out with help from the folks over at the Angular IRC channel... are you, by chance, setting up your controller though ng-controller? I had:
<div ng-controller="myCtrl">
... when it should have been removed:
<div>
... because I was setting up the controller in the resolve on the router. That's what I was doing and it was causing this very issue. You can see more here:
https://stackoverflow.com/a/18305423/1306982
foo_list <- is the js file for this being loaded in the your html page in a script tag? it just mightbe the case that when you have forgotten to include factory/service/controller and actually have forgotten to include it in a script tag in the index/app html page (or require shims)
Okay just saw your comment and extending the answer here cos its easier to do it here.
Your code where you declare the controller should read like
App.controller('FoosCtrl',
['$scope', '$location', 'Foos', /* comment out foo_list here*/
function($scope, $location, Foos, foo_list /* this remains */) {
...
}
when the route is getting changed things you mention in 'resolve' would get resolved by ui-router. But it the place where you are declaring your FoosCtrl you don't actually have a provider for it to resolve.
Give this a try i had a similar case like this last week.
Just as a heads up, I just had a similar issue which was caused by adding the resolve-variables as a dependency to the controller while not having set up the response funciton in the $stateProvider.state() yet.
Adding the resolve function fixed the missing dependency
(I still don't quite get why - I'd be glad if anyone could share his knowledge in the comments)