AngularJS - $templateCache is not defined - angularjs

I am trying to load a template file in an AngularStrap popover, however I am having trouble using $templateCache. I seem to be a step further back than the other SO questions, hence this seemingly double one.
Following the API docs I added a <script type="text/ng-template" id="popoverTemplate.html"></script> right before the closing </body> tag. When I use <div ng-include="'popoverTemplate.html'"></div> on my page, I get nothing. If I try using console.log($templateCache.get("popoverTemplate.html")) I get "$templateCache is not defined", which leads me to assume I am missing a crucial step. However, I can't find how to do it in the docs or other SO questions.
EDIT:
Injecting the service was the missing link. However, when I inject the service, the controller's other function no longer works, but if you inject al the function's parameters the working code becomes:
(function() {
"use strict";
angular.module("app").controller("managerController", ["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
imageHierarchyRepository.query(function(data) {
$scope.hierarchies = data;
});
var template = $templateCache.get("popoverTemplate.html");
console.log(template);
}]);
})();

To use the template script tag . You have to insert it inside the angular application. That is inside the element with the ng-app attribute or the element used to bootstrap the app if you don't use the ng-app tag.
<body ng-app="myapp">
<div ng-template="'myTemplate.html'"></div>
<script type="text/ng-template" id="myTemplate.html">
// whate ever
</script>
</body>
If you want to retrieve the template on a component of the application then you need to inject the service where you want to consume it:
controller('FooCtrl', ['$templateCache', function ($templateCache) {
var template = $templateCache.get('myTemplate.html');
}]);
Or
controller('FooCtlr', FooCtrl);
FooCtrl ($templateCache) {};
FooCtrl.$inject = ['$templateCache'];
EDIT
Do not register two controllers with the same name because then you override the first one with the last one.
(function() {
"use strict";
angular.module("app").controller("managerController",["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
var template = $templateCache.get("popoverTemplate.html");
console.log(template);
imageHierarchyRepository.query(function(data) {
$scope.hierarchies = data;
});
}]);
})();

Small addition: Although there are few ways to achieve your goals, like wrapping your whole HTML in <script> tags and all that, the best approach for me was to add the $templateCache logic into each Angular directive. This way, I could avoid using any external packages like grunt angular-templates (which is excellent but overkill for my app).
angular.module('MyApp')
.directive('MyDirective', ['$templateCache', function($templateCache) {
return {
restrict: 'E',
template: $templateCache.get('MyTemplate').data,
controller: 'MyController',
controllerAs: 'MyController'
};
}]).run(function($templateCache, $http) {
$http.get('templates/MyTemplate.html').then(function(response) {
$templateCache.put('MyTemplate', response);
})
});
Hope this helps!

Related

Angular.js 1.2 separating Controllers and Directives using an IIFE

I seem to come across an error when I try to define a controller within a directive that is wrapped in an IIFE. Although I could fixed this by adding ng-controller on the div in tableHelper.html. I was wondering the code below returns tableHelperCtrl as undefined.
Using angular.js 1.2.29
app.module.js
(function () {
'use strict';
angular.module('app', [
]);
})();
tableHelper.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('tableHelperCtrl', tableHelperCtrl);
function tableHelperCtrl() {
var vm = this;
vm.data = 'some data'
}
})();
tableHelper.directive.js
(function () {
'use strict';
angular
.module('app')
.directive('tableHelper', tableHelper);
function tableHelper() {
var directive = {
restrict: 'A',
templateUrl: './src/app/tableHelper/tableHelper.html',
link: link,
controller: tableHelperCtrl,
controllerAs: 'vm'
};
return directive;
}
}
})();
tableHelper.html
<div>
<p>Table Helpers Directive</p>
<table>
<thead></thead>
<td>{{vm}}</td>
</table>
</div>
You should not assign them the same controller. Give them a controller each and make them communicate through scope (using isolate scopes too if needed) or through a service.
There are a couple of issues with your directive code. Suresh's comment about wrapping the name of your controller in quotes seems to be one issue, although I've seen it work without them, I couldn't get it.
You've also got an extra closing curly brace, an you didn't define link although I guess we could assume that you've got it somewhere but left it out.
One more item is since you've defined your controller as 'vm', you want to use vm.data in your html instead of just vm.
Here's a plunker that shows it working with these changes.

Accessing directive from a different module

I have two different modules , first one contains controller second directive.
Basically i want the directive to be rendered in my view.
But as modules for directiveandcontroller are different, its giving error.
If i give same module then it ressolves my issue by i want a generic module serving all controllers.
controller
angular.module('SlamModuleCtrl')
.controller('SlambookExt',['$scope','$route','SlambookCollection', function($scope,$route) {
console.log("slam controller")
}]);
Directive
angular.module('Genericmodule')
.directive('appVersion', ['version', function (version) {
return {
restrict: 'E',
template: '<h1>version1</h1>'
}
}])
View
<div ng-controller="SlambookExt">
<app-version>1</app-version>
</div>
When instantiating slamModuleCtrl, you need to specify genericModule as a dependency.
Or use a parent module that loads both those modules as dependencies and use that parent module as your ng-app.
angular.module('parentModule',['slamModuleCtrl','genericModue'])
This is just a plausible solution because both your modules look right to me. So I'm guessing that the version is not showing up because the module hasn't been loaded
Chanthu is correct you need to specify a parent module that has dependencies on your other modules but you also pass a array of dependencies for your other modules, in this case they don't have any.
declare your modules and add them in to the parent module like so...
var controllerModule = angular.module('controllerModule', []);
var directiveModule = angular.module('directiveModule', []);
controllerModule.controller('mainController', function($scope) {
$scope.hello = 'Hello';
})
directiveModule.directive('myDirective', function() {
return {
template: '{{hello}}'
};
});
angular.module('app', ['controllerModule', 'directiveModule']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<body ng-app="app" ng-controller="mainController">
<my-directive></my-directive>
</body>
code snippet shows another module directive and uses the binding from another module controller

AngularJS - Running a function once on load

I am trying to run an $http function when my AngularJS application first loads.
This $http function needs to finish before any of the controllers in my application could properly function. How would I go about doing this? This sounds like a promise, but it sounds like I would be creating a promise in each controller...
I currently have the function that I want to run first like this:
app.run(function() {
$http.get('link').success(function(data) {
// success function. The data that I get from this HTTP call will be saved to a service.
}).error(function(error) {
});
});
However, sometimes the controller will load before the http call finishes.
The problem
Angular is not dynamic, you cannot add controller dynamically neither factory, etc. Also you cannot defer controller bootstrap, angular loads everything together, and it's quite disadvantage (will be fixed in Angular 2)
The cure
But javascript itself has very important feature - closure, which works anywhere, anytime.
And angular has some internal services that can be injected outside of angular ecosystem, even into browser console. Those services injected as shown below. We technically could use anything else (jQuery.ajax, window.fetch, or even with XMLHttpRequest), but let's stick with total angular solution
var $http_injected = angular.injector(["ng"]).get("$http");
The act
First of all, we defer whole angular app bootstrap, inject http service. Then you make your needed request, receive data and then closure get's to work, we pass received data into some service, or we could also assign in to some angular.constant or angular.value but let's just make demo with angular.service, so when your service has data, bootstrap whole app, so that all controllers get initialized with your needed data
Basically that kind of tasks solved like this
<body>
<div ng-controller="Controller1">
<b>Controller1</b>
{{text}}
{{setting.data.name}}
</div>
<hr>
<div ng-controller="Controller2">
<b>Controller2</b>
{{text}}
{{setting.data.name}}
</div>
<script>
//define preloader
var $http_injected = angular.injector(["ng"]).get("$http");
$http_injected.get('http://jsonplaceholder.typicode.com/users/1').then(function(successResponse) {
//define app
angular.module('app', []);
//define test controllers
//note, usually we see 'controller1 loaded' text before 'settings applied', because controller initialized with this data, but in this demo, we will not see 'controller1 loaded' text, as we use closure to assign data, so it's instantly changed
angular.module('app').controller('Controller1', function($scope, AppSetting) {
$scope.text = 'controller1 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
angular.module('app').controller('Controller2', function($scope, AppSetting) {
$scope.text = 'controller2 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
//define test services, note we assign it here, it's possible
//because of javascript awesomeness (closure)
angular.module('app').service('AppSetting', function() {
this.setting = successResponse;
});
//bootstrap app, we cannot use ng-app, as it loads app instantly
//but we bootstrap it manually when you settings come
angular.bootstrap(document.body, ['app']);
});
</script>
</body>
Plunker demo
You can do this when you configure your routes
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'main.html',
resolve: {
data: ['$http',
function($http)
{
return $http.get('/api/data').then(
function success(response) { return response.data.rows[0]; },
function error(reason) { return false; }
);
}
]
}
});
}]);
Similar question:
AngularJS - routeProvider resolve calling a service method
AngularJS: $routeProvider when resolve $http returns response obj instead of my obj
Heres a plunkr I found using a service, which is what I would recommend.
http://plnkr.co/edit/XKGC1h?p=info

How do I make a directive's functions globally available?

Imagine I have a singleton user-interface element that I want to provide services to the entire application.
The following "works", in that setMessage() is available anywhere in the application, via $rootScope:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.js"></script>
<body ng-app="myApp">
<script>
angular.module('myApp', [])
.directive('myDirective', function($rootScope) {
return {
scope : {},
template: '<div>Status: {{contents}}</div>',
controller: function($scope) {
$rootScope.setMessage = function(contents) {
$scope.contents = contents;
};
}
};
});
</script>
<div my-directive=""></div>
<button ng-click="setMessage('clicked')">Click Me</button>
</body> </html>
It works, but I don't like it. It just doesn't feel anglish to me. I have been toying with the idea of create a service that exports a function to set the value and another function to get it, but that doesn't smell much better.
Any suggestions?

AngularJS directive loaded with RequireJS not compiling

I'm in the beginning stages of building a large app with AngularJS and RequireJS. Everything loads find but directives aren't manipulating the DOM as they should. No errors are being reported and rest of the app works fine: Views are loaded and $scope is bindable. Examining the console shows that all the files loaded. I'm assuming this is a lazy load issue in that my directive is simply not loading at the correct time. I'd appreciate any insight into how to properly load directives in this regard. Unless it's a part of Angular's jqLite, please refrain from suggesting jQuery.
config.js
require.config({
paths: { angular: '../vendor/angular' }
shim: { angular: { exports: 'angular' } }
});
require(['angular'], function(angular) {
angular.bootstrap(document, ['myApp']);
});
myApp.js
define(['angular', 'angular-resource'], function (angular) {
return angular.module('myApp', ['ngResource']);
});
routing.js
define(['myApp', 'controllers/mainCtrl'], function (myApp) {
return myApp.config(['$routeProvider', function($routeProvider) {
...
}]);
});
mainCtrl.js
define(['myApp', 'directives/myDirective'], function (myApp) {
return myApp.controller('mainCtrl', ['$scope', function ($scope) {
...
}]);
});
myDirective.js
require(['myApp'], function (myApp) {
myApp.directive('superman', [function() {
return {
restrict: 'C',
template: '<div>Here I am to save the day</div>'
}
}])
});
home.html
<div class="superman">This should be replaced</div>
home.html is a partial that's loaded into ng-view
Angular cannot load directives after it has been bootstrapped. My suggestion is:
Make myDirective.js do a define(), not a require()
Make sure myDirective.js is run before the require(['angular'],...) statement in config.js, e.g. do require(['angular','myDirective'],...). For this to work, myDirective should be shimmed to depend on angular - thanks # David Grinberg.
As a sidenote, take a look at this in Stackoverflow/this in GitHub, we have been trying to do RequireJS + Angular play together.

Resources