Template using in Angularjs - angularjs

i'm using ng-duallist template. I got it here : https://github.com/tushariscoolster/ng-duallist
I want to use twice in the same html controller. I have created new variable for it but content is always same so how can I separate it?

I want to add vm2 to other data content but always same value added two duallist
hmtl code
directives code
var existingEntries = [];
var vm = this;
vm.property = 'controller';
activate();
function activate() {
vm.leftValue = [];
vm.rightValue = [];
vm.addValue = [];
vm.removeValue = [];
function loadMoreLeft() {
for (var i = 0; i < $scope.reasonOfLack.length; i++) {
vm.leftValue.push({
'name': $scope.reasonOfLack[i]
});
}
};
function loadMoreRight() {
}
vm.options = {
leftContainerScrollEnd: function () {
},
rightContainerScrollEnd: function () {
},
leftContainerSearch: function (text) {
console.log(text)
vm.leftValue = $filter('filter')(leftValue, {
'name': text
})
},
rightContainerSearch: function (text) {
vm.rightValue = $filter('filter')(rightValue, {
'name': text
})
},
leftContainerLabel: 'Uygunsuzluk Sebepleri',
rightContainerLabel: 'Seçilen Uyunsuzluk Sebepleri',
onMoveRight: function () {
console.log('right');
console.log(vm.addValue);
},
onMoveLeft: function () {
console.log('left');
console.log(vm.removeValue);
}
};
loadMoreLeft();
var leftValue = angular.copy(vm.leftValue)
var rightValue = angular.copy(vm.rightValue)
}

Related

Directive Parameter Not Initializing on First Load In AngularJs

I'va made a Dropdown directive, i'm trying to assign methods on passing parameter to directive and i'll call these method from controller.
but on first load i'm not getting the assign method in controller but when i'm assigning it on second load (i.e on dropdown change event)and it's working fine.
how can i get the methods on first load of directive in the calling controller after first load.
here is the Directive:
"use strict";
myApp.directive("selectDirective", [function () {
return {
restrict: "E",
template: '<select class="form-control input-sm dropdown" data-ng-model="model.args.selectedItem" data-ng-options="item[model.args.displayField] for item in model.args.source" data-ng-change="model.itemChange(model.args.selectedItem)"><option value="">Select Any Item</option></select>',
scope: {
},
bindToController: { args: "=" },
controller: function () {
var self = this;
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
if (self.args.method == undefined) {
self.args.method = {};
}
if (self.args.isDisabled == undefined) {
self.args.isDisabled = false;
}
if (self.args.displayField == undefined) {
self.args.displayField = '';
//alert('Display Field is blank for dropdown control.')
}
if (self.args.valueField == undefined) {
self.args.valueField = '';
//alert('Value Field is blank for dropdown control.')
}
if (self.args.source == undefined) {
self.args.source = {};
}
if (self.args.hide == undefined) {
self.args.hide = false;
}
}
//here i'm assigning the methods in passing parameter
var assignMethod = function () {
self.args.method =
{
setEnable: function (args) {
self.args.isDisabled = !args;
},
setVisible: function (args) {
self.args.hide = !args;
},
getText: function () {
return self.args.selectedText;
},
getValue: function () {
return self.args.selectedValue;
},
setItem: function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
}
}
self.itemChange = function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
initializeControl();
assignMethod();
},
controllerAs: 'model'
}
}]);
Here is the Calling Controller Code:
"use strict";
myApp.controller("homeController", [function () {
var self = this;
var initializeControl = function () {
var myList = [{ id: 1, name: 'List1', value: 'List1' },
{ id: 2, name: 'List2', value: 'List2' }];
self.argsParam = {
displayField: 'name',
valueField: "value",
source: myList,
selectecText: '',
selectecValue: ''
};
self.clickMe = function () {
debugger;
var item = { id: 2, name: 'List2', value: 'List2' };
self.argsParam.method.setItem(item);
}
};
initializeControl();
}]);
View where i used the directive:
<div class="cold-md-12" ng-controller="homeController as model">
<h1>Home Page</h1>
<select-directive args="model.argsParam"></select-directive>
<input type="button" value="Click" ng-click="model.clickMe()" />
</div>
Scenario:
If assigned method called second time inside directive on dropdown-change event then i can get these method on passing param.
i.e
self.itemChange = function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
// here i'm assigning these method on change event then it's working fine after changing the value otherwise no success
assignMethod();
}
}
So, How i can i get the methods assign in the passing parameter on
First load of the directive?
I've moved the Controller Content to Link function in Directive and
it's working fine, but I still didn't get any idea how my previous code
not worked as expected.
Directive Code:
'use strict';
var testApp = angular.module('TestApp', []);
testApp.directive('sampleDirective', ['$http', function () {
return {
restrict: "E",
scope: {},
bindToController: { args: '=' },
template: '<div class="row">' +
'<select class="form-control"' +
'data-ng-model="model.args.selectedItem"' +
'data-ng-options="item[model.args.displayField] for item in model.args.source"' +
'data-ng-change="model.itemChange(model.args.selectedItem)">' +
'<option value="">Select Any Item</option>' +
'</select>' +
'</div>',
link: function (scope, element, attrs) {
var self = scope.model;
debugger;
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
if (self.args.method == undefined) {
self.args.method = {};
}
if (self.args.isDisabled == undefined) {
self.args.isDisabled = false;
}
if (self.args.displayField == undefined) {
self.args.displayField = '';
alert('Display Field is blank for dropdown control.')
}
if (self.args.valueField == undefined) {
self.args.valueField = '';
alert('Value Field is blank for dropdown control.')
}
if (self.args.source == undefined) {
self.args.source = {};
}
if (self.args.hide == undefined) {
self.args.hide = false;
}
}
var assignMethod = function () {
self.args.method =
{
setEnable: function (args) {
self.args.isDisabled = !args;
},
setVisible: function (args) {
self.args.hide = !args;
},
getText: function () {
return self.args.selectedText;
},
getValue: function () {
return self.args.selectedValue;
},
setItem: function (item) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
};
}
self.itemChange = function (item) {
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
initializeControl();
assignMethod();
},
controller: function () {
},
controllerAs: 'model'
}
}]);

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Backbone Modal with Q.promise issue

We have a method (onOpenNotitiesClicked) for showing a Modal view for entering notes. We have implemented the Backbone Modal plugin for this (https://github.com/awkward/backbone.modal).
There are two situations:
There are not yet notes in the backend: initialize and render the
modal
There are already notes in the backend => first collect them and
then pass the notes to the modal (initialize) and then render
In the first situation it works fine! The modal is shown.
In the second situation, the modal is not shown.
I have debugged both situations and in both situations, alle methods are executed and in the elements, I see the HTML of the modal view.
I suspect this looses some data during the Q/promise data get, but I can't see what/where/how/why....
Anyone any idea what I am doing wrong? Or what I am missing?
The creation of the modal:
onOpenNotitieClicked: function (event) {
var $element, taak, taakId, id, options = {};
$element = this.$(event.currentTarget).closest("li");
id = $element.data("id");
taakId = $element.data("taak-id");
taak = this.getCurrentTask(event);
options.taakKey = id;
options.taakId = taakId;
options.heeftNotities = taak.heeftNotities;
options.datacontroller = this.datacontroller;
this.notitiesOptions = options;
// this.renderNotitieModal(options);
if (taak.heeftNotities) {
this.getActiviteitNotities(taakId).then(_.bind(this.onSuccessGetNotities, this), _.bind(this.onErrorGetNotities, this));
} else {
this.renderNotitieModal(this.notitiesOptions);
}
},
In case there are notes to be collected:
getActiviteitNotities: function (taakId) {
return this.datacontroller.getNotities(taakId);
},
onSuccessGetNotities: function (notities) {
this.notitiesOptions.notities = notities;
this.renderNotitieModal(this.notitiesOptions);
},
onErrorGetNotities: function () {
this.renderNotitieModal(this.notitiesOptions);
},
To get the notes from the backend, Q/promises is used.
getNotities: function (taakId, refresh, klantorderId) {
return Q.promise(function (resolve, reject) {
var options = {};
if (!this.notitiesCollection || this.taakId !== taakId || refresh) {
delete this.notitiesCollection;
this.notitiesCollection = this.createCollection("NotitiesCollection", {
id: this.taakId,
resource: this.NOTITIES_RESOURCE
});
if (taakId) {
this.taakId = taakId;
options = {
data: {
parentId: this.taakId
}
};
} else if (klantorderId) {
options = {
data: {
klantorderId: klantorderId
}
};
}
resolve(this.notitiesCollection.fetch(options));
} else if (this.notitiesCollection) {
resolve(this.notitiesCollection.toJSON());
} else {
reject("ERROR");
}
}.bind(this));
},
Notities.js (the modal view):
(function () {
"use strict";
App.Bewaking.modals.BewakingNotitieModal = Backbone.Modal.extend({
template: JST.bewaking_notitie_modal, //jshint ignore:line
title: "Notities",
formatter: new App.Main.helpers.Formatter(),
events: {
"click #save-notitie": "onSaveNotitieClicked"
},
initialize: function (options) {
this.taakId = options.taakId;
this.taakKey = options.taakKey;
this.datacontroller = options.datacontroller;
this.notities = options.notities;
},
afterRender: function () {
console.log("afterRender");
this.$notitieModal = this.$("#notitieModal");
this.$nieuweNotitie = this.$("#nieuwe-notitie");
this.$notitieErrorTekst = this.$("#notitie-error-tekst");
this.$notitieModal.on("shown.bs.modal", function () {
this.$nieuweNotitie.focus();
}.bind(this));
},
render: function () {
console.log(this.notities);
this.$el.html(this.template({
formatter: this.formatter,
notities: this.notities
}));
return this;
}
});
}());

Variables between factories in angular.js

I'm currently learning angular and have hit a roadblock.
The second factory (shown below) makes an http request like this: http://example.com/api/get_post/?post_id=7129&callback=JSON_CALLBACK');
I want the post ID to be a variable. So depending on which blog title is clicked, I can pass the correct variable into that http request.
In other words, I guess I want to take a result from the first factory (blogAPIservice) and use it in the second factory.
Makes sense??
<!-- FACTORIES -->
angular.module('blogApp.services',[])
.factory('blogAPIservice',function($http) {
var blogAPI = [];
var blogs = $http.jsonp('http://example.com/api/get_recent_posts/?count=10&callback=JSON_CALLBACK');
blogs.success(function(data) {
$.each(data.posts, function(i, blog) {
var fromNow = moment(blog.date).fromNow();
blogAPI.push({
url: blog.url,
title: blog.title,
excerpt: blog.excerpt,
date : fromNow,
id: blog.id
})
});
});
var factory = {};
factory.getBlogs = function () {
return blogAPI;
};
return factory;
})
.factory('singlePostService',function($http) {
var singleAPI = [];
var postID = '7129';
var singlePost = $http.jsonp('http://example.com/api/get_post/?post_id=7129&callback=JSON_CALLBACK');
singlePost.success(function(data) {
singleAPI.push({
title: data.post.title,
content: data.post.content
})
});
var factory = {};
factory.getSinglePost = function () {
return singleAPI;
};
return factory;
})
And here are the controllers:
angular.module('blogApp.controllers', [])
.controller('resultsController',function($scope, blogAPIservice) {
$scope.keywordFilter = null;
$scope.blogs = [];
init();
function init() {
$scope.blogs = blogAPIservice.getBlogs();
}
function grabID() {
$(this).attr('rel');
}
})
.controller('singlePostController',function($scope, singlePostService) {
$scope.keywordFilter = null;
$scope.singlePost = [];
init();
function init() {
$scope.singlePost = singlePostService.getSinglePost();
}
})
And finally the markup:
<li ng-repeat="blog in blogs">
{{ blog.title }}
</li>
You can inject the first service into the second one like this:
.factory('singlePostService',function($http, blogAPIservice) {
//Do something with blogAPIservice
}
For more information about depenency injection read the docs

Backbone/Marionette ItemView not rendering on model change

Already a couple of hours struggle trying to solve this...
Although the model gets fetched correctly and I can verify it as the view gets informed of the model's 'change' event, it just does not render.
At startup, the default model data ('Test Project'), is correctly displayed in the view, but after the model is refreshed, the view is not refreshed.
I tried to show a new view in the layout after model refresh but it did not change much...
Any idea or opinion about this ?
App.Project = function () {
var Project = {};
var ProjectModel = Backbone.Model.extend({
defaults:{
id: 0,
name: "Test Project",
intro: "",
desc: ""
},
initialize: function () {
// Flag fetch status to avoid multiple simultaneous calls
this.loading = false;
var self = this;
App.vent.on("project:display", function (_id) { self.fetchProject(_id); });
},
fetchProject: function (_id) {
if (this.loading)
return true;
this.loading = true;
var self = this;
var id = _id;
this.url = 'data.project_'+id+'.json';
this.fetch({
success: function (_data) {
self.loading = false;
},
error: function () {
self.loading = false;
}
});
}
});
Project.Details = new ProjectModel();
var Layout = Backbone.Marionette.Layout.extend({
template: "#project-layout",
regions: { details: "#project_details" }
});
Project.initializeLayout = function () {
Project.layout = new Layout();
App.content.show(App.Project.layout);
};
App.addInitializer(function () {
App.Project.initializeLayout();
});
Project.display = function () {
App.Project.Views.showDetails(Project.Details);
App.vent.trigger("project:display", 1);
}
return Project;
}();
App.Project.Views = function () {
var Views = {};
var DetailView = Backbone.Marionette.ItemView.extend({
template: "#project-details-template",
tagName: "div",
initialize: function () {
//this.listenTo(this.model, "change", this.render, this);
},
modelEvents: {
'change': "modelChanged"
},
modelChanged: function() {
console.log(this.model);
this.render();
}
});
Views.showDetails = function (_project) {
var projectView = new DetailView({model: _project});
App.Project.layout.details.show(projectView);
};
return Views;
}();
App.ProjectRouting = function () {
var ProjectRouting = {};
ProjectRouting.Router = Backbone.Marionette.AppRouter.extend({
initialize: function (_options) {
this.route('project/', "displayProject", _options.controller.display);
}
});
App.vent.on("project:display", function (_id) {
App.navigate("project/");
});
App.addInitializer(function (_options) {
ProjectRouting.router = new ProjectRouting.Router({
controller: App.Project
});
});
return ProjectRouting;
}();

Resources