how can I access ngModel from directive controller - directive

function prMySelects() {
var ddo = {
restrict: 'E',
templateUrl: 'template.html',
require: '?ngModel',
scope: {
ngModel: '='
},
controller: prMySelectsController,
controllerAs: 'vm',
bindToController: true
};
return ddo;
}
function prMySelectsController($locale) {
...
}
I need do some checks inside directive controller and set ngModel.$setValidity('some', false), but getting ngModel is not defined error. Injecting ngModel didn't help...
PS I know that I can access it in link, but is it possible to reach ngModel controller in directive controller?

This sort of functionality is best done inside the link function for a directive.
function prMySelects() {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attributes, ngModel) {
scope.theModel = ngModel;
},
controller: function() {
var vm = this;
vm.theModel.$setViewValue...
}
}
}
In this case, your are actually getting a hook into the ngModel controller and its not required that you actually specifiy it on the scope.

Related

angular-ui-bootstrap causes unknown provider error when minified

After adding angular-ui-bootstrap and running grunt serve on my yeoman app, it runs perfectly and the modal I want to show is displayed correctly, but once I do a grunt build, I get an unknown provider error in my console.
<!-- This is what I added in my index.html -->
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
// In app.js I have
angular.module('yeomanApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.bootstrap'
])
and in the controller,
.controller('myCntrl', function ($modal) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.showDeleteWarning = function () {
var modalInstance = $modal.open({
templateUrl: 'deleteWarning.html',
controller: ModalInstanceCtrl,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {});
};
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
deleteVent();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
};
Likely that you need to inject your controller dependency...
https://docs.angularjs.org/tutorial/step_05#a-note-on-minfication
.controller('myCntrl', ['$modal', function ($modal) {
/* Controller Code Here... */
}]);
I know this is an old question, but I'll post my answer here for people who come across this problem in the future.
I came across this exact problem before. The cause of your errors during minification is most likely your 'var ModalInstanceCtrl'.
Here's how I got my code to work:
var modalInstance = $modal.open({
templateUrl: 'deleteWarning.html',
controller: 'ModalInstanceCtrl', //change this to a string
resolve: {
items: function () {
return $scope.items;
}
}
});
and this line:
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
to:
angular.module('myModule').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
For anyone who just encountered this problem, maybe this will help.
We use customModalDefaults and customModalOptions, so we had to turn the whole return $modal.open(tempModalDefaults).result; in the show function to the following:
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
return $modal.open({
backdrop: customModalDefaults.backdrop,
keyboard: customModalDefaults.keyboard,
modalFade: customModalDefaults.modalFade,
templateUrl: customModalDefaults.templateUrl,
size: customModalDefaults.size,
controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
} ]
}).result;
};
I just ran into this problem on only one of many modals used throughout my application, and it turned out my problem was not using explicit function annotation in the resolve block of the modal configuration.
var modalInstance = $uibModal.open({
templateUrl: 'preferences.html',
controller: 'preferencesCtrl as ctrl', // this external controller was using explicit function annotation...
resolve: {
parent: [function() {
return ctrl;
}],
sectorList: ['preferencesService', function(preferencesService) { // but this was not!
return preferencesService.getSectors();
}]
}
});
Hope this saves someone else a gray hair or two...

Angular JS directive "#" $scope in-$digestion

Given:
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
classToAdd: '#'
},
template:
'<div class="{{classToAdd}}"></div>'
};
});
I'm testing a spec where classToAdd is being statically coded in the template:
<my-directive class-to-add="foo"></my-directive>
and the classToAdd attribute is only being recognized if I $digest $rootScope, and not $scope.
Why this is the case?
Working fiddle.
The reason the shown fiddle was failing, is that "foo" is bound to the $rootScope, not the local $scope.
The solution is to set the scope variable, interpolate it using {{foo}} (since we're using "#" in the isolate scope)
it('should bind to the class-to-add attribute when we $digest $scope', function () {
// Arrange
template = '<my-directive class-to-add="{{foo}}"></my-directive>';
compiledDirective = $compile(template)($scope);
directiveEl = compiledDirective.find('div');
$scope.foo = "bar"
// Act
$scope.$digest();
// Assert
expect(directiveEl.hasClass('bar')).toBe(true);
});
you can write your code like this:
angular.module('app',[])
.controller('ctrl',['$scope',function($scope){
$scope.myClass="myClass";
}])
.directive('myDirective',function(){
return {
restrict:'E',
scope:{ classToAdd: '#' },
transclude:true,
replace: true,
template:'<div class="{{classToAdd}}" ng-transclude></div>',
link: function(scope, iElement, iAttrs){
console.log(scope);
console.log(iAttrs);
}
}
})
and here is a working DEMO
notice the console for logs and under the hood stuff.

How do I call an action method on Controller from the outside, with the same behavior by clicking {{action}}

Please look at this code...
```
App.BooksRoute = Ember.Route.extend({
model: return function () {
return this.store.find('books');
}
});
App.BooksController = Ember.ArrayController.extend({
actions: {
updateData: function () {
console.log("updateData is called!");
var books = this.filter(function () {
return true;
});
for(var i=0; i<books.length; i++) {
//doSomething…
}
}
}
});
```
I want to call the updateData action on BooksController from the outside.
I tried this code.
App.__container__.lookup("controller:books").send('updateData');
It works actually. But, in the updateData action, the this is different from the one in which updateData was called by clicking {{action 'updateData'}} on books template.
In the case of clicking {{action 'updateData'}}, the this.filter() method in updateData action will return books models.
But, In the case of calling App.__container__.lookup("controller:books").send('updateData');, the this.filter() method in updateData action will return nothing.
How do I call the updateData action on BooksController from the outside, with the same behavior by clicking {{action 'updateData'}}.
I would appreciate knowing about it.
(I'm using Ember.js 1.0.0)
You can use either bind or jQuery.proxy. bind is provided in JS since version 1.8.5, so it's pretty safe to use unless you need to support very old browsers. http://kangax.github.io/es5-compat-table/
Either way, you're basically manually scoping the this object.
So, if you have this IndexController, and you wanted to trigger raiseAlert from outside the app.
App.IndexController = Ember.ArrayController.extend({
testValue : "fooBar!",
actions : {
raiseAlert : function(source){
alert( source + " " + this.get('testValue') );
}
}
});
With bind :
function externalAlertBind(){
var controller = App.__container__.lookup("controller:index");
var boundSend = controller.send.bind(controller);
boundSend('raiseAlert','External Bind');
}
With jQuery.proxy
function externalAlertProxy(){
var controller = App.__container__.lookup("controller:index");
var proxySend = jQuery.proxy(controller.send,controller);
proxySend('raiseAlert','External Proxy');
}
Interestingly this seems to be OK without using either bind or proxy in this JSBin.
function externalAlert(){
var controller = App.__container__.lookup("controller:index");
controller.send('raiseAlert','External');
}
Here's a JSBin showing all of these: http://jsbin.com/ucanam/1080/edit
[UPDATE] : Another JSBin that calls filter in the action : http://jsbin.com/ucanam/1082/edit
[UPDATE 2] : I got things to work by looking up "controller:booksIndex" instead of "controller:books-index".
Here's a JSBin : http://jsbin.com/ICaMimo/1/edit
And the way to see it work (since the routes are weird) : http://jsbin.com/ICaMimo/1#/index
This solved my similar issue
Read more about action boubling here: http://emberjs.com/guides/templates/actions/#toc_action-bubbling
SpeedMind.ApplicationRoute = Ember.Route.extend({
actions: {
// This makes sure that all calls to the {{action 'goBack'}}
// in the end is run by the application-controllers implementation
// using the boubling action system. (controller->route->parentroutes)
goBack: function() {
this.controllerFor('application').send('goBack');
}
},
};
SpeedMind.ApplicationController = Ember.Controller.extend({
actions: {
goBack: function(){
console.log("This is the real goBack method definition!");
}
},
});
You could just have the ember action call your method rather than handling it inside of the action itself.
App.BooksController = Ember.ArrayController.extend({
actions: {
fireUpdateData: function(){
App.BooksController.updateData();
}
},
// This is outside of the action
updateData: function () {
console.log("updateData is called!");
var books = this.filter(function () {
return true;
});
for(var i=0; i<books.length; i++) {
//doSomething…
}
}
});
Now whenever you want to call updateData(), just use
App.BooksController.updateData();
Or in the case of a handlebars file
{{action "fireUpdateData"}}

AngularJS - Formatting ng-model before template is rendered in custom directive

I am creating a custom directive in Angular JS. And I want to format the ng-model before the template renders.
This is what I have so far:
app.js
app.directive('editInPlace', function() {
return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});
html
<edit-in-place ng-model="unformattedDate"></edit-in-place>
I want to format the unformattedDate value before it is entered in the ngModel of the template. Something like this:
template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'
but that gives me an error. How to do this?
ngModel exposes its controller ngModelController API and offers you a way to do so.
In your directive, you can add $formatters that do exactly what you need and $parsers, that do the other way around (parse the value before it goes to the model).
This is how you should go:
app.directive('editInPlace', function($filter) {
var dateFilter = $filter('dateFormat');
return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
link: function(scope, element, attr, ngModelController) {
ngModelController.$formatters.unshift(function(valueFromModel) {
// what you return here will be passed to the text field
return dateFilter(valueFromModel);
});
ngModelController.$parsers.push(function(valueFromInput) {
// put the inverse logic, to transform formatted data into model data
// what you return here, will be stored in the $scope
return ...;
});
},
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});

What is the best approach to use Disqus in a single page application?

What is the best approach to use Disqus in a single page application?
I see that the angular js docs has implemented it successfully.
Currently our approach looks like is this in our AngularJS app, but it seems unstable, is hard to test, and loads wrong thread ids (the same thread gets loaded almost everywhere).
'use strict';
angular.module('studentportalenApp.components')
.directive('disqusComponent',['$log', '$rootScope', function($log, $rootScope) {
var _initDisqus = function _initDisqus(attrs)
{
if(window.DISQUS) {
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = attrs.threadId;
this.disqus_container_id = 'disqus_thread';
this.page.url = attrs.permalinkUrl;
}
});
}
else
{
$log.error('window.DISQUS did not exist before directive was loaded.');
}
}
//Destroy DISQUS bindings just before route change, to properly dispose of listeners and frame (postMessage nullpointer exception)
$rootScope.$on('$routeChangeStart', function() {
if(window.DISQUS) {
DISQUS.reset();
}
});
var _linkFn = function link(scope, element, attrs) {
_initDisqus(attrs);
}
return {
replace: true,
template: '<div id="disqus_thread"></div>',
link: _linkFn
};
}]);
I also wanted to include Disqus on my AngularJS-powered blog. I found the existing solutions a bit unwieldy so I wrote my own directive:
.directive('dirDisqus', function($window) {
return {
restrict: 'E',
scope: {
disqus_shortname: '#disqusShortname',
disqus_identifier: '#disqusIdentifier',
disqus_title: '#disqusTitle',
disqus_url: '#disqusUrl',
disqus_category_id: '#disqusCategoryId',
disqus_disable_mobile: '#disqusDisableMobile',
readyToBind: "#"
},
template: '<div id="disqus_thread"></div>comments powered by <span class="logo-disqus">Disqus</span>',
link: function(scope) {
scope.$watch("readyToBind", function(isReady) {
// If the directive has been called without the 'ready-to-bind' attribute, we
// set the default to "true" so that Disqus will be loaded straight away.
if ( !angular.isDefined( isReady ) ) {
isReady = "true";
}
if (scope.$eval(isReady)) {
// put the config variables into separate global vars so that the Disqus script can see them
$window.disqus_shortname = scope.disqus_shortname;
$window.disqus_identifier = scope.disqus_identifier;
$window.disqus_title = scope.disqus_title;
$window.disqus_url = scope.disqus_url;
$window.disqus_category_id = scope.disqus_category_id;
$window.disqus_disable_mobile = scope.disqus_disable_mobile;
// get the remote Disqus script and insert it into the DOM
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + scope.disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
});
}
};
});
Advantages
The main advantage of this approach, I think, is that it keeps things simple. Once you have registered the directive with your app, you don't need to write any JavaScript or set any config values in your JavaScript. All configuration is handled by passing attributes in the directive tag like so:
<dir-disqus disqus-shortname="YOUR_DISQUS_SHORTNAME"
disqus-identifier="{{ article.id }}"
disqus-title="{{ article.title }}"
...>
</dir-disqus>
Also, you don't need to alter your index.html file to include the Disqus .js file - the directive will dynamically load it when it is ready. This means that all that extra .js will only get loaded on those pages that actually use the Disqus directive.
You can see the full source and documentation here on GitHub
Caveat
The above will only work properly when your site is in HTML5Mode, i.e. not using the "#" in your URLs. I am updating the code on GitHub so the directive will work when not using HTML5Mode, but be warned that you must set a hashPrefix of "!" to make "hashbang" URLs - e.g. www.mysite.com/#!/page/123. This is a limitation imposed by Disqus - see http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites
I know nothing about Disqus, but according to the AngularJS Documentation source code:
They bind a load function to afterPartialLoaded:
$scope.afterPartialLoaded = function() {
var currentPageId = $location.path();
$scope.partialTitle = $scope.currentPage.shortName;
$window._gaq.push(['_trackPageview', currentPageId]);
loadDisqus(currentPageId);
};
Then, they simply add the html to the page:
function loadDisqus(currentPageId) {
// http://docs.disqus.com/help/2/
window.disqus_shortname = 'angularjs-next';
window.disqus_identifier = currentPageId;
window.disqus_url = 'http://docs.angularjs.org' + currentPageId;
// http://docs.disqus.com/developers/universal/
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://angularjs.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
angular.element(document.getElementById('disqus_thread')).html('');
}
This is how we solved it.
We load DISQUS in the body of index.html, and resets it whenever there is a directive using it.
Directive:
'use strict';
angular.module('fooApp.directives')
.directive('disqusComponent',['$window', '$log', function($window, $log) {
var _initDisqus = function _initDisqus(scope)
{
if($window.DISQUS) {
$window.DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = scope.threadId;
this.disqus_container_id = 'disqus_thread';
}
});
}
else
{
$log.error('window.DISQUS did not exist before directive was loaded.');
}
}
var _linkFn = function link(scope, element, attrs) {
element.html('<div id="disqus_thread"></div>');
_initDisqus(scope);
}
return {
replace: true,
template: 'false',
scope: {
threadId: '#'
},
link: _linkFn
};
}]);
This is how it can be tested:
'use strict';
describe('Directive: Disqus', function() {
var element, $window, $rootScope, $compile;
beforeEach(function() {
module('fooApp.directives', function($provide) {
$provide.decorator('$window', function($delegate) {
$delegate.DISQUS = {
reset: jasmine.createSpy()
};
return $delegate;
});
});
inject(function(_$rootScope_, _$compile_, _$window_) {
$window = _$window_;
$rootScope = _$rootScope_;
$compile = _$compile_;
});
});
it('should place a div with id disqus_thread in DOM', function() {
element = angular.element('<disqus-component></disqus-component>');
element = $compile(element)($rootScope);
expect(element.html()).toBe('<div id="disqus_thread"></div>');
});
it('should do a call to DISQUS.reset on load', function() {
element = angular.element('<disqus-component thread-id="TESTTHREAD"></disqus-component>');
element = $compile(element)($rootScope);
var resetFn = $window.DISQUS.reset;
expect(resetFn).toHaveBeenCalled();
});
});