I am trying to get angularjs to play nicely with local templates that override bootstrap ones.
I had initially use the same file path (uib/template/carousel/carousel.html for example) which is fine when published, but locally it doesn't work.
So, I found this soluton:
Angular ui bootstrap directive template missing
They have said you can override the template with a new url with the $provide service.
So I have done this:
'use strict';
angular.module('core').config(coreConfig);
function coreConfig($provide) {
$provide.decorator('uibCarousel', function ($delegate) {
console.log($delegate[0]);
$delegate[0].templateUrl = 'bootstrap/carousel/carousel.html';
return $delegate;
});
};
which should work.
my core module looks like this:
'use strict';
angular.module('core', [
'ngCookies',
'ngNotify',
'ngResource',
'ngSimpleCache',
'ui.bootstrap',
'ui.bootstrap.tpls',
'ui.router',
'ui.select',
// -- remove for brevity -- //
]);
As you can see, I have the ui.bootstrap.tpls module loaded, so in theory, my code should work.
Can anyone think of a reason that it won't?
Sorry for all the comment spam. I think I have found the answer to your issue.
You must append Directive to a directive when defining the decorator:
function coreConfig($provide) {
$provide.decorator('uibCarouselDirective', function ($delegate) {
console.log($delegate[0]);
$delegate[0].templateUrl = 'bootstrap/carousel/carousel.html';
return $delegate;
});
};
From the docs:
Decorators have different rules for different services. This is
because services are registered in different ways. Services are
selected by name, however filters and directives are selected by
appending "Filter" or "Directive" to the end of the name. The
$delegate provided is dictated by the type of service.
https://docs.angularjs.org/guide/decorators
This is an example from my own (working) code:
$provide.decorator("uibDatepickerPopupDirective", [
"$delegate",
function($delegate) {
var directive = $delegate[0];
// removed for brevity
return $delegate;
}
]);
Related
I have configurations.js file which having
var configurationModule = angular.module('configuration', ['restangular', 'notification']);
configurationModule.factory('clientConfigSvc', function (notificationMgr, $interpolate, $injector) {
function getConfig(configKey) {
return getNestedPropertiesByString(activeEnvironment, configKey);
}
}
and having another javascript file with below code
angular.module('ds.coupons').factory('CouponsREST', ['Restangular', 'SiteConfigSvc', 'settings',function (Restangular, siteConfig, settings, configurationModule) {
configSvc.getConfig('services.baseUrl'); /// need to call this function
}
Actually i want function configSvc.getConfig inside second angular factory
Yes After tired of trying lots of solution, today morning working on moving train got idea to fix, dont know if its correct way but its working. but still looking for correct fix if mine was not correct as per angularjs practise.
Here is my solution.
1. I added configuration module in app.js alogn with other
window.app = angular.module('ds.app', [
'restangular',
'ui.select',
'ui.router',
'ds.shared',
'ds.utils',
'ds.i18n',
'configuration']);
I added clientConfigSVC in my factory where i want to use configuration function
angular.module('ds.coupons')
.factory('CouponsREST', ['Restangular', 'SiteConfigSvc','settings', 'clientConfigSvc',
function(Restangular, siteConfig, settings, clientConfig) { }
and then inside CouponsREST factory with function clientConfig.getConfig() i am getting value
When trying to implement the session part in the tutorial of John Papa Pluralsight Video.
I got the following error:
Uncaught TypeError: Object # has no method 'extendQ'
(function () {
'use strict';
var app = angular.module('app', [
// Angular modules
'ngAnimate', // animations
'ngRoute', // routing
'ngSanitize', // sanitizes html bindings (ex: sidebar.js)
// Custom modules
'common', // common functions, logger, spinner
'common.bootstrap', // bootstrap dialog wrapper functions
// 3rd Party Modules
'ui.bootstrap', // ui-bootstrap (ex: carousel, pagination, dialog)
//'breeze.angular.q'
]);
// Handle routing errors and success events
app.run(['$route', '$rootScope', '$q', function ($route, $rootScope, $q) {
// Include $route to kick start the router.
breeze.core.extendQ($rootScope, $q);
//use$q($rootScope,$q);
}]);
})();
It's important to know that the version of breeze that I'm working on is newer than the used on the original video.
I search for some answers on the breeze website and I've found this:
The to$q has been deprecated. It is superseded by the Breeze Angular Service.
But I didn't make it work on the tutorial example. How to change the deprecated implementation with the new one?
UPDATE:
this link helped solve the problem:
http://www.breezejs.com/documentation/breeze-angular-service
The breeze library was updated and the answer is on this link: http://www.breezejs.com/documentation/breeze-angular-service
Specifically this code from the bottom of the post:
Migration is pretty painless.
Remove the breeze.angular.q.js script from your project.
Uninstall-Package Breeze.Angular.Q if you used NuGet.
Install breeze.angular.js as explained above.
Update your index.html, changing breeze.angular.q.js to breeze.angular.js.
Update your app module to depend on "breeze.angular".
Find the one place in your code where you call "use$q" and replace it with the "breeze" dependency.
For example, you might go from this:
var app = angular.module('app', [
// ... other dependencies ...
'breeze.angular.q' // tells breeze to use $q instead of Q.js
]);
app.run(['$q','use$q', function ($q, use$q) {
use$q($q);
}]);
to this:
var app = angular.module('app', [
// ... other dependencies ...
'breeze.angular'
]);
app.run(['breeze', function () { }]);
You should also track down and eliminate code that configures Breeze to use the "backingStore" model library adapter and $http. For example, you could go from this:
function configBreeze($q, $http, use$q) {
// use $q for promises
use$q($q);
// use the current module's $http for ajax calls
var ajax = breeze.config.initializeAdapterInstance('ajax', 'angular');
ajax.setHttp($http);
// the native Breeze 'backingStore' works for Angular
breeze.config.initializeAdapterInstance('modelLibrary', 'backingStore', true);
breeze.NamingConvention.camelCase.setAsDefault();
}
to this:
function configBreeze() {
breeze.NamingConvention.camelCase.setAsDefault();
While taking the same course by John Papa I also hit breeze.core.extendQ not available on step 4.10.
This is what I did to solve the issue:
1 - In app.js pass breeze dependency directly:
// Handle routing errors and success events
// Trigger breeze configuration
app.run(['$route', 'breeze', function($route, breeze)
{
// Include $route to kick start the router.
}]);
2 - In datacontext.js do:
return EntityQuery.from('Sessions')
.select('id, title, code, speakerId, trackId, timeSlotId, roomId, level, tags')
.orderBy(orderBy)
.toType('Session')
.using(manager).execute()
.then(querySucceeded, _queryFailed);
You can also get rid of breeze.to$q.shim.js from index.html and delete the file from the \Scripts folder in the project since it's not needed anymore.
Here's the updated source code of the same project I'm doing now [ including the fixes ].
I'm trying for the first time to use AngularJS in conjunction with RequireJS using this guide as a basis. As far I can tell after a lot of debugging I'm loading all my modules in the correct order, but when the application runs Angular throws an Error / Exception with the following message:
Argument 'fn' is not a function, got string from myApp
I've seen this message before due to syntax errors, so even though I've looked trough the code multiple times I won't rule out the possibility of a simple syntax error. Not making a Fiddle just yet in case it is something as simple as a syntax error, but I'll of course do so if requested.
Update: I just noticed when setting ng-app="myApp" in the <html> tag I also get an additional error,
No module: myApp
Update II: Okay, it turns out it indeed was an syntax error in the only file not included below. I am though still left with the problem from update I.
RequireJS bootstrap
'use strict';
define([
'require',
'angular',
'app/myApp/app',
'app/myApp/routes'
], function(require, ng) {
require(['domReady'], function(domReady) {
ng.bootstrap(domReady, ['myApp']);
});
});
app.js
'use strict';
define([
'angular',
'./controllers/index'
], function(ng) {
return ng.module('myApp', [
'myApp.controllers'
]);
}
);
controllers/index
'use strict';
define([
'./front-page-ctrl'
], function() {
});
controllers/module
'use strict';
define(['angular'], function (ng) {
return ng.module('myApp.controllers', []);
});
controllers/front-page-ctrl
'use strict';
define(['./module'], function(controllers) {
controllers.
controller('FrontPageCtrl', ['$scope',
function($scope) {
console.log('I\'m alive!');
}
]);
});
Delete ng-app="myApp" from your html.
Because it has bootstrapped manually
ng.bootstrap(domReady, ['myApp']);
RequireJS docs on Dom ready state:
Since DOM ready is a common application need, ideally the nested
functions in the API above could be avoided. The domReady module also
implements the Loader Plugin API, so you can use the loader plugin
syntax (notice the ! in the domReady dependency) to force the
require() callback function to wait for the DOM to be ready before
executing. domReady will return the current document when used as a
loader plugin:
So, when you require 'domReady' the result is a function:
function domReady(callback) {
if (isPageLoaded) {
callback(doc);
} else {
readyCalls.push(callback);
}
return domReady;
}
But when you append the domReady string with ! sign the result will be the actual document element:
'use strict';
define([
'require',
'angular',
'app/myApp/app',
'app/myApp/routes'
], function(require, ng) {
require(['domReady!'], function(domReady) {
// domReady is now a document element
ng.bootstrap(domReady, ['myApp']);
});
});
I'm using AngularJS and requireJS and I'm using this seed template to help me to get Angular to place nicely with requireJS which can be found here LINK
At the moment I'm trying to integrate AngularUI's calendar into the project but I keep recieving the error "Cannot call method 'map' of undefined" when the calendar code is in calendarCtrl.js with the scope injected into this controller. However when I place the code directly in the controller (controllers.js) the calendar works.
Plunkr link: LINK
In angular the internal injectors for all of the scope controls are initialized by the app. You managed to detach your app from your controller definition so angular didn't know how to inject the pieces needed for the use of the $scope object.
Option 1
So to get this to work so you need to either define an app/module that get's passed into the space where the control is defined:
define(['angular'], function (angular) {
'use strict';
return angular.module('TP.controllers', []);
});
calendar control:
define([
"jquery",
"controllers",
"jqueryui",
"full_calendar",
"calendar",
],
function($, controllers) {
return controllers
.controller('calendarCtrl', ['$scope', function($scope) {
....
In which case you'd have to include every individual controller in your top level application like:
define([
'angular',
'controllers',
'calendarCtrl',
'full_calendar',
'calendar'
], function (angular, controllers) {
'use strict';
return angular.module('TP', ['TP.controllers', 'ui.calendar']);
});
Which to some degree defeats the purpose of using AMD.
Option 2
A better option is to define your calendar as it's own module then define it as a child of controllers. This maintains the angular injection chain so the scope has the proper context when initializing the calendar actions.
Defining the controllers root:
define(['angular', 'calendarCtrl'], function (angular) {
'use strict';
return angular.module('TP.controllers', ['calendarCtrl']);
});
Defining the calendar controller:
define([
"jquery",
"angular",
"jqueryui",
"full_calendar",
"calendar",
],
function($, angular) {
return angular.module('calendarCtrl', [])
.controller('calendarCtrl', ['$scope', function($scope) {
...
Working plunker of this version at http://plnkr.co/edit/Xo41pqEdmB9uCUsEEzHe?p=preview.
EDIT: I have managed to get my unit tests running - I moved the code containing the services to a different file and a different module, made this new module a requirement for fooBar module, and then before each "it" block is called, introduced the code beforeEach(module(<new_service_module_name)). However, my application still won't run. No errors in console either. This is the only issue that remains - that when I use global scope for controllers definition, the application works, but when I use angular.module.controller - it does not.
I have a file app.js that contains the following:
'use strict';
var app = angular.module('fooBar', []);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/form-view.html',
controller: FormViewCtrl
}).
when('/resultDisplay', {
templateUrl: 'partials/table-view.html',
controller: TableViewCtrl
}).
otherwise({redirectTo: '/'});
}]);
app.service('searchResults', function() {
var results = {};
return {
getResults: function() {
return results;
},
setResults: function(resultData) {
results = resultData;
}
};
});
I have another file controllers.js that contains the following:
'use strict';
var app = angular.module('fooBar', []);
app.controller('FormViewCtrl', ['$scope', '$location', '$http', 'searchResults',
function ($scope, $location, $http, searchResults) {
//Controller code
}]);
searchResults is a service that I created that simply has getter and setter methods. The controller above uses the setter method, hence the service is injected into it.
As a result, my application just does not run! If I change the controller code to be global like this:
function ($scope, $location, $http, searchResults) {
//Controller code
}
then the application works!
Also, if I use the global scope, then the following unit test case works:
'use strict';
/*jasmine specs for controllers go here*/
describe('Foo Bar', function() {
describe('FormViewCtrl', function() {
var scope, ctrl;
beforeEach(module('fooBar'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('FormViewCtrl', {$scope: scope});
}));
}
//"it" blocks
}
If I revert to the module scope, I get the error -
Error: Unknown provider: searchResultsProvider <- searchResults
Thus, by using global scope my application and unit tests run but by using app.controller, they seem to break.
Another point that I have noted is that if I include the controller code in app.js instead of controllers.js, then the application and unit tests start working again. But I cannot include them in the same file - how do I get this to run in the angular scope without breaking the application and unit tests?
You don't need to go that route. You can use the modular approach, but the issue is with your second parameter.
In your app.js you have this:
var app = angular.module('fooBar', []);
Then in your controller, you have this:
var app = angular.module('fooBar', []);
What you're doing there is defining the module twice. If you're simply trying to attach to the app module, you cannot pass in the second parameter (the empty array: []), as this creates a brand new module, overwriting the first.
Here is how I do it (based on this article for architecting large AngularJS apps.
app.js:
angular.module('fooBar',['fooBar.controllers', 'fooBar.services']);
angular.module('fooBar.controllers',[]);
angular.module('fooBar.services', []);
...etc
controllers.js
angular.module('foobar.controllers') // notice the lack of second parameter
.controller('FormViewCtrl', function($scope) {
//controller stuffs
});
Or, for very large projects, the recommendation is NOT to group your top-level modules by type (directives, filters, services, controllers), but instead by features (including all of your partials... the reason for this is total modularity - you can create a new module, with the same name, new partials & code, drop it in to your project as a replacement, and it will simiply work), e.g.
app.js
angular.module('fooBar',['fooBar.formView', 'fooBar.otherView']);
angular.module('fooBar.formView',[]);
angular.module('fooBar.otherView', []);
...etc
and then in a formView folder hanging off web root, you THEN separate out your files based on type, such as:
formView.directives
formView.controllers
formView.services
formView.filters
And then, in each of those files, you open with:
angular.module('formView')
.controller('formViewCtrl', function($scope) {
angular.module('formView')
.factory('Service', function() {
etc etc
HTH
Ok - I finally figured it out. Basically, if you wish to use the module scope and not the global scope, then we need to do the following (if you have a setup like app.js and controllers.js):
In app.js, define the module scope:
var myApp = angular.module(<module_name>, [<dependencies>]);
In controllers.js, do not define myApp again - instead, use it directly like:
myApp.controller(..);
That did the trick - my application and unit tests are now working correctly!
It is best practice to have only one global variable, your app and attach all the needed module functionality to that so your app is initiated with
var app = angular.module('app',[ /* Dependencies */ ]);
in your controller.js you have initiated it again into a new variable, losing all the services and config you had attached to it before, only initiate your app variable once, doing it again is making you lose the service you attached to it
and then to add a service (Factory version)
app.factory('NewLogic',[ /* Dependencies */ , function( /* Dependencies */ ) {
return {
function1: function(){
/* function1 code */
}
}
}]);
for a controller
app.controller('NewController',[ '$scope' /* Dependencies */ , function( $scope /* Dependencies */ ) {
$scope.function1 = function(){
/* function1 code */
};
}
}]);
and for directives and config is similar too where you create your one app module and attach all the needed controllers, directives and services to it but all contained within the parent app module variable.
I have read time and time again that for javascript it is best practice to only ever have one global variable so angularjs architecture really fills that requirement nicely,
Oh and the array wrapper for dependencies is not actually needed but will create a mess of global variables and break app completely if you want to minify your JS so good idea to always stick to the best practice and not do work arounds to get thing to work
In my case, I've defined a new provider, say, xyz
angular.module('test')
.provider('xyz', function () {
....
});
When you were to config the above provider, you've inject it with 'Provider' string appended.
Ex:
angular.module('App', ['test'])
.config(function (xyzProvider) {
// do something with xyzProvider....
});
If you inject the above provider without the 'Provider' string, you'll get the similar error in OP.