I have a list that looks like this:
Store 1
Section A
Section B
and so on...
Store 2
Section A
and so on...
So I open a modal window to create a new store. I return the store when I close the window, and so far that's working great!
<div ng-repeat="store in global.user.company2.store">
I need to push the callback store to $scope.global.user.company2.store[?]
modalInstance.result.then(function (newStore) {
// How do I get the IndexOf value of store?
// This is one of the stores in the ng-repeat
$scope.global.user.company2.store[???].section.push(newStore)
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
The way I'm sending a selected store into the modal is with resolve
$scope.createSection = function (size) {
var modalInstance = $modal.open({
templateUrl: 'createSection.html',
controller: 'SectionModal',
size: size,
resolve: {
items: function () {
// $scope.radio.model === store
// $scope.radio.model2 === section
return $scope.radio;
}
}
});
UPDATE: Here's a basic plunker http://plnkr.co/edit/UGN4niAO9nQETqhg8lxn
The radio model buttons aren't working. If you change resolve items to $scope.radio.model, the modal breaks. So I left it as is. I think maybe it has to do with the btn-radio being part of angular-ui-bootstrap?
When resolving your modal, box your returned object with the array index of the object.
For example:
$modalInstance.close({ radio: $scope.radio, index: $scope.items.indexOf($scope.radio) } );
Then, when resolving your modal's promise, simply unbox your object:
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem.radio;
$scope.selectedIndex = selectedItem.index;
}, function () {});
See the Angular-Bootstrap docs for more details.
Related
I am having no joy with implementing require: {} property as part of an angular component. Allow me to demonstrate with an example I have.
This is the component/directive that supposed to fetch a list of judgements. Nothing very fancy, just a simple factory call.
// judgements.component.js
function JudgementsController(GetJudgements) {
var ctrl = this;
ctrl.Get = function () {
GetJudgements.get().$promise.then(
function (data) {
ctrl.Judgements = data.judgements;
}, function (error) {
// show error message
});
}
ctrl.$onInit = function () {
ctrl.Get();
};
}
angular
.module('App')
//.component('cJudgements', {
// controller: JudgementsController,
//});
.directive('cJudgements', function () {
return {
scope: true,
controller: 'JudgementsController',
//bindToController: true,
};
});
I am trying to implement component require property to give me access to ctrl.Judgements from the above component/directive as follows:
// list.component.js
function ListController(GetList, GetJudgements) {
var ctrl = this;
ctrl.list = [];
ctrl.Get = function () {
GetList.get().$promise.then(
function (data) {
ctrl.list = data.list;
}, function (error) {
// show error message
});
};
//ctrl.GetJudgements = function () {
// GetJudgements.get().$promise.then(
// function (data) {
// ctrl.Judgements = data.judgements;
// }, function (error) {
// // show error message
// });
//}
ctrl.$onInit = function () {
ctrl.Get();
//ctrl.GetJudgements();
};
}
angular
.module('App')
.component('cTheList', {
bindings: {
listid: '<',
},
controller: ListController,
controllerAs: 'ctrl',
require: {
jCtrl: 'cJudgements',
},
template: `
<c-list-item ng-repeat="item in ctrl.list"
item="item"
judgements="ctrl.Judgements"></c-list-item>
<!--
obviously the reference to judgements here needs to change
or even better to be moved into require of cListItem component
-->
`,
});
Nice and simple no magic involved. A keen reader probably noticed GetJudgement service call in the ListController. This is what I am trying to remove from TheList component using require property.
The reason? Is actually simple. I want to stop database being hammered by Judgement requests as much as possible. It's a static list and there is really no need to request it more than once per instance of the app.
So far I have only been successful with receiving the following error message:
Error: $compile:ctreq
Missing Required Controller
Controller 'cJudgements', required by directive 'cTheList', can't be found!
Can anyone see what I am doing wrong?
PS: I am using angular 1.5
PSS: I do not mind which way cJudgement is implemented (directive or component).
PSSS: If someone wonders I have tried using jCtrl: '^cJudgements'.
PSSSS: And multiple ^s for that matter just in case.
Edit
#Kindzoku posted a link to the article that I have read before posting the question. I hope this also helps someone in understanding $onInit and require in Angular 1.5+.
Plunker
Due to popular demand I made a plunker example.
You should use required components in this.$onInit = function(){}
Here is a good article https://toddmotto.com/on-init-require-object-syntax-angular-component/
The $onInit in your case should be written like this:
ctrl.$onInit = function () {
ctrl.jCtrl.Get();
};
#iiminov has the right answer. No parent HTML c-judgements was defined.
Working plunker.
I'm working on a meteor app that uses angular-meteor and ng-table. The dataset of the ng-table is from a collection. You can add rows to the table dynamically via a modal form. The dataset is reactive and changes the view once there's a change in the collection. I'm watching for status changes of the item (QUEUED, PROCESSING, CREATED).
Thing is, if the table is on page 2 and the status changes (any change in the dataset), the table is redrawn and goes back to page 2. Is there a way to make it stay on the current page even with dataset changes?
Here's a sample of what I have so far:
(function () {
'use strict';
function myController($scope, $reactive, ngTableParams, ngTableEventsChannel, myService) {
$reactive(this).attach($scope);
this.subscribe('myCollection');
this.currentPage = 1;
this.helpers({
tableParams: () => {
return new ngTableParams({
page: this.currentPage
}, {
//this is just a simple collection call
dataset: myService.getItems().fetch()
});
}
});
$scope.$watch('vm.tableParams', (params) => {
//not triggered :(
ngTableEventsChannel.onDatasetChanged(() => {
console.log('data changed');
tableParams.page($scope.currentPage);
}, $scope, tableParams);
ngTableEventsChannel.onPagesChanged(() => {
$scope.currentPage = tableParams.page();
}, $scope, tableParams);
});
}
angular.module('MyApp').controller('MyController', myController);
})();
The onDatasetChanged event isn't being triggered. I was going to change the page there but I'm not sure if that's a good idea anyway.
I'm using the Angular UI bootstrap modal and I ran into a bit of a problem.
I want to call a function when the bootstrap modal dismiss animation is finished. The code block below will call the cancel() function as soon as the modal starts to be dismissed - and NOT when the modal dismiss animation has finished.
Angular UI does not use events, so there is no 'hidden.bs.modal' event being fired (at least, not to my knowledge).
var instance = $modal.open({...});
instance.result.then(function(data) {
return success(data);
}, function() {
return cancel();
})
The cancel() block immediately runs when the modal starts to close. I need code to execute when the closing animation for the Bootstrap modal finishes.
How can I achieve this with angular UI?
Component for reference:
https://angular-ui.github.io/bootstrap/#/modal
Thanks!
A little late but hope it still helps! You can hijack the uib-modal-window directive and check when its scope gets destroyed (it is an isolated scope directive). The scope is destroyed when the modal is finally removed from the document. I would also use a service to encapsulate the functionality:
Service
app.service('Modals', function ($uibModal, $q) {
var service = this,
// Unique class prefix
WINDOW_CLASS_PREFIX = 'modal-window-interceptor-',
// Map to save created modal instances (key is unique class)
openedWindows = {};
this.open = function (options) {
// create unique class
var windowClass = _.uniqueId(WINDOW_CLASS_PREFIX);
// check if we already have a defined class
if (options.windowClass) {
options.windowClass += ' ' + windowClass;
} else {
options.windowClass = windowClass;
}
// create new modal instance
var instance = $uibModal.open(options);
// attach a new promise which will be resolved when the modal is removed
var removedDeferred = $q.defer();
instance.removed = removedDeferred.promise;
// remember instance in internal map
openedWindows[windowClass] = {
instance: instance,
removedDeferred: removedDeferred
};
return instance;
};
this.afterRemove = function (modalElement) {
// get the unique window class assigned to the modal
var windowClass = _.find(_.keys(openedWindows), function (windowClass) {
return modalElement.hasClass(windowClass);
});
// check if we have found a valid class
if (!windowClass || !openedWindows[windowClass]) {
return;
}
// get the deferred object, resolve and clean up
var removedDeferred = openedWindows[windowClass].removedDeferred;
removedDeferred.resolve();
delete openedWindows[windowClass];
};
return this;
});
Directive
app.directive('uibModalWindow', function (Modals) {
return {
link: function (scope, element) {
scope.$on('$destroy', function () {
Modals.afterRemove(element);
});
}
}
});
And use it in your controller as follows:
app.controller('MainCtrl', function ($scope, Modals) {
$scope.openModal = function () {
var instance = Modals.open({
template: '<div class="modal-body">Close Me</div>' +
'<div class="modal-footer"><a class="btn btn-default" ng-click="$close()">Close</a></div>'
});
instance.result.finally(function () {
alert('result');
});
instance.removed.then(function () {
alert('closed');
});
};
});
I also wrote a blog post about it here.
I am not very familiar with the CKEDITOR API yet and now I got stuck trying to find the way to create placeholders inside of the CKEDITOR editable area.The expected behaviour for the placeholder - to dissappear on user interaction with it, allowing to edit the content instead.
I know that there is already a placeholder plugin (http://ckeditor.com/addon/placeholder) but its behaviour is not what I am looking for.
To be more specific, the question is: is it possible to subscribe for some events on the particular element inside of the CKEDITOR?
Working in the angular context I am able to compile my html before it is passed to the CKEDITOR ng-model
$scope.html = $compile('<div><span text-placeholder >Placeholder</span></div>')($scope).html();
But then I fail trying to set click events inside of the directive:
.directive('textPlaceholder', [ function () {
return {
restrict: 'A',
link: function ($scope, $element) {
//THIS DOES NOT WORK UNFORTUNATELY
$element.on('click', function () {
console.log('clicked');
})
}
}
}])
Any thoughts?
UPDATE: For now I came up with the solution to implement simple plugin and then reference it in the CKEDITOR config:
(function () {
CKEDITOR.plugins.add('text-placeholder', {
init: function (editor) {
editor.on('key', function (evt) {
var el = $(CKEDITOR.instances.editor1.getSelection().getNative().baseNode.parentElement);
if (el.hasClass('text-placeholder')) {
el.remove();
}
});
}
});
})();
Looks ugly for me. Any feedback is appreciated.
This seems to be a final Solution:
CKEDITOR.plugins.add('text-placeholder', {
init: function (editor) {
editor.on('contentDom', function () {
var editable = editor.editable();
editable.attachListener(editable, 'click', function (event) {
var $placeholder = $(event.data.$.target).closest('.text-placeholder');
if ($placeholder.length > 0) {
var selection = editor.getSelection();
selection.selectElement(selection.getStartElement());
}
});
});
}
});
This applies the selection on the element with "text-placeholder" class when user focuses it inside of the editable area
Update:
See example
You inspired me to write one myself, using the above example as a starting point. In my use case I wanted to take placeholder text from an attribute on the editor -- data-placeholder -- and display it in the editor. When the editor gets focus, the placeholder text disappears. When the editor blurs -- if no user content has been entered -- the placeholder text is displayed again. Additionally, I set a data-placeholder-showing attribute so that I can, for example, use CSS to make the placeholder text gray. Here's my code:
CKEDITOR.plugins.add('text-placeholder', {
init: function (editor) {
var placeholder = editor.element.getAttribute('data-placeholder');
editor.on('contentDom', function () {
if (placeholder) {
editor.setData(placeholder);
editor.element.setAttribute('data-placeholder-showing', true);
}
});
editor.on('focus', function() {
if (editor.getData() === placeholder) {
editor.element.setAttribute('data-placeholder-showing', false);
editor.setData('');
}
});
editor.on('blur', function() {
if (placeholder && editor.getData().length === 0) {
editor.element.setAttribute('data-placeholder-showing', true);
editor.setData(placeholder);
}
});
}
});
Scenario
I have a carousel in modal A which is made up of a bunch of slides. Each slide is a credit card. One of the slides however allows the user to launch modal B; this modal (Modal B) is used to record new credit card details. An object from modal B is then returned to A, after it's closed, which should then be added to the carousel in modal A.
Modal A
Modal B
Naturally I want this credit card (slide) to have the same functionality as the others, for example, if I click on it it should become the default credit card, highlighted by a grey background and a green tick on the top right.
I'm using slick-slider for the carousel and to add a new slide it needs a string so I'm trying to angularize my HTML string before adding it:
// Adds the new credit card
$scope.addNewCreditCard = function (newCreditCard) {
var slider = $('.slick-slider');
if (slider) {
var tempData = $scope.creditCardDetails;
$scope.creditCardDetails = null;
var htmlString = '<div class="creditcard" ng-click="fooBar()" '+
'<p>Some text</p>'+
'</div>';
// Angularize the string
var ngString = $compile(htmlString)($scope);
slider.slickAdd( ngString, 0, true);
// Update the object
$scope.creditCardDetails = tempData;
} else {
$log.error('Not found');
}
};
fooBar() is just a function that outputs an 'I've been clicked!' message to the console but it isn't being called when clicked.
Question
How do I go about compiling this string so it gets that function attached?
Thanks in advance
Note: This is not a directive, the modal, courtesy of angular bootstrap, is called like so:
$scope.showAddNewCreditCardModal = function () {
var modalInstance = $modal.open({
templateUrl: 'modules/common/partials/modals/addcreditcard/modal.addcreditcard.html',
backdrop: true,
windowClass: 'modal-add-credit-card',
controller: 'AddCreditCardCtrl',
size: 'lg',
scope: $scope
});
modalInstance.result.then(
function (success) {
// Below is a dummy that fills in the blanks for the card
var newCreditCard = {
'ElectronicPaymentAccountID': '123456789',
'ElectronicPaymentAccountType': 'ACP',
'CreditCardNumber': success.cardnumber,
'ExpirationDate': success.expmm + '/' + success.expyy,
'PreferredAccount': 'false',
'AccountName': ':o',
'PaymentTypeCode': ''
};
$scope.addNewCreditCard(newCreditCard);
},
function (error) {
$log.debug('Error: ' + JSON.stringify(error));
}
);
};
Before to answer your question, I want to get your attention on your condition:
var slider = $('.slick-slider');
if (slider) { ... }
I don't know if this is angular syntax but I think you should use this kind of condition:
var slider = $('.slick-slider');
if (typeof slider[0] != "undefined") { ... }
/* OR if (typeof slider[0] === "object") { ... } */
To answer, I don't really use AngularJS, but referring to "AngularJS + JQuery : How to get dynamic content working in angularjs", you maybe have to do something like:
var ngString.html($compile(htmlString)($scope));
I hope this informations help you.