Angular - getting value from directive in the controller - javascript

I need to pass a selected value from a directive that I am using in several places. It is a select input field that I need to get a selected value from.
This is how the directive looks like:
angular.module('quiz.directives')
.directive('fancySelect', function($rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: 'templates/directives/fancySelect.html',
scope: {
title: '#',
model: '=',
options: '=',
multiple: '=',
enable: '=',
onChange: '&',
class: '#'
},
link: function(scope) {
scope.showOptions = false;
scope.displayValues = [];
scope.$watch('enable', function(enable) {
if (!enable && scope.showOptions) {
scope.toggleShowOptions(false);
}
});
scope.toggleShowOptions = function(show) {
if (!scope.enable) {
return;
}
if (show === undefined) {
show = !scope.showOptions;
}
if (show) {
$rootScope.$broadcast('fancySelect:hideAll');
}
$timeout(function() {
scope.showOptions = show;
});
};
scope.toggleValue = function(value) {
if (!value) {
return;
}
if (!scope.multiple) {
scope.model = value;
console.log(scope.model);
return;
}
var index = scope.model.indexOf(value);
if (index >= 0) {
scope.model.splice(index, 1);
}
else {
scope.model.push(value);
}
if (scope.onChange) {
scope.onChange();
}
};
scope.getDisplayValues = function() {
if (!scope.options || !scope.model) {
return [];
}
if (!scope.multiple && scope.model) {
return scope.options.filter(function(opt) {
return opt.id == scope.model;
});
}
return scope.options.filter(function(opt) {
return scope.model.indexOf(opt.id) >= 0;
});
};
$rootScope.$on('fancySelect:hideAll', function() {
scope.showOptions = false;
});
}
};
});
When I do console.log(scope.model); I get the selected value, but I am not sure how to get it and use it in my controller?
This is the controller:
angular.module('quiz.controllers')
.controller('ProfileController', function(
$scope,
$state,
$stateParams,
UserService,
$auth,
MessageService,
$ionicLoading,
AppSettings,
$timeout,
AvatarService,
PushService,
$http
) {
$scope.user = UserService.get();
$scope.profilePromise = {};
if ($scope.user.player.avatar == ""){
$scope.user.player.avatar = AvatarService.getRandom();
}
$http.get(AppSettings.apiUrl + '/years')
.then(function(result) {
$scope.years = result.data;
});
$scope.updateUser = function(form) {
if (!form.$valid) {
var message = "Ugyldig data i skjema. Sjekk felter markert med rødt.";
MessageService.alertMessage(message);
return;
}
saveUser($scope.user);
};
$scope.getNextAvatar = function() {
$scope.user.player.avatar = AvatarService.getNext($scope.user.player.avatar);
};
$scope.getPreviousAvatar = function() {
$scope.user.player.avatar = AvatarService.getPrevious($scope.user.player.avatar);
};
var saveUser = function(user) {
$scope.profilePromise = UserService.save(user);
$scope.profilePromise.then(function(result) {
$scope.user = result.data.user;
PushService.init();
PushService.getDeviceId().then(function(id) {
UserService.addDevice(id);
});
if ($stateParams.register) {
$state.go('main.front');
}
}, function(error) {
var message = "Kunne ikke lagre bruker. Melding fra server: " + error.data.message;
MessageService.alertMessage(message);
});
};
});

You already have an onChange binding in the scope, so why don't you use that one?
In your directive:
if (scope.onChange) {
scope.onChange({ $value: scope.model });
}
Then pass a controller function to your directive:
<fancy-select on-change="onChange($value)"></fancy-select>
In your controller:
$scope.onChange = function(val) {
// do something with the value
}

Related

Console Error in $element, while using $mdDialog of AngularJS Material

I'm trying to solve this error that shows in the console, it only occurs on the server, in my localhost the modal works correctly. Here's the error (click to open its link):
I have a view with the controller:
.when('/aseguradora', {
templateUrl: 'views/insuranceagentdashboard.html',
controller: 'InsuranceagentdashboardCtrl'
})
This is the controller:
angular.module('virtualApp').controller('InsuranceagentdashboardCtrl', ['$http', '$scope', 'pager', 'Dialogs', function($http, $scope, pager, Dialogs) {..
Inside the controller I have a function that executes the modal, (Dialogs is a service):
$scope.showCosignerFormDialog = function(insuranceRequest) {
Dialogs.cosignerFormdialog(insuranceRequest);
}
In HTML I have an md-button with an ng-click
<md-button class="md-color-green" ng-click="showCosignerFormDialog(insuranceRequest)">VER SOLICITUD</md-button>
This is the Dialog service that executes the modal:
dialogs.cosignerFormdialog = function(insuranceRequest) {
return $mdDialog.show({
templateUrl: 'views/cosignerformdialog.html',
autoWrap: false,
controller: 'IdentityVerificationWizardCtrl',
locals: {
listing: insuranceRequest
},
preserveScope: true,
escapeToClose: false,
fullscreen: true,
clickOutsideToClose: true
});
};
I do not know why this error can occur in the console being in the URL of the server, if I am in my localhost I do not get this error ...
THIS IS CONTROLLER identityverificationwizard.js:
angular.module('virtualApp').controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', '$element', function($scope, upload, $http, listing, $routeParams, $location, Dialogs, $element) {
$scope.propertyListing = listing;
$scope.insuranceStudyContactInfo = {};
$scope.insuranceStudyJobInfo = {};
$scope.insuranceStudyFinancialInfo = {};
$scope.insuranceStudyAssets = {};
$scope.identityInfo = {
date : moment('01/01/2000', 'DD/MM/YYYY').toDate()
};
$scope.virtualSignatureInfo = {};
$scope.isCorporation = 'false';
$scope.insuranceStudyJobInfo.publicOfficer = false;
$scope.insuranceStudyJobInfo.managesPublicFunds = false;
$scope.insuranceStudyJobInfo.linkedToRenownedPeople = false;
$scope.insuranceStudyJobInfo.vatResponsible = false;
$scope.insuranceStudyJobInfo.greatContributor = false;
$scope.insuranceStudyFinancialInfo.doImport = false;
$scope.insuranceStudyFinancialInfo.doExport = false;
$scope.insuranceStudyFinancialInfo.doInvest = false;
$scope.insuranceStudyFinancialInfo.doCurrencyExchange = false;
$scope.insuranceStudyFinancialInfo.doPayServices = false;
$scope.insuranceStudyFinancialInfo.doPayLoans = false;
$scope.insuranceStudyFinancialInfo.doTransactions = false;
$scope.rentProcessId = $scope.propertyListing.rentProcessId;
$scope.cosignerKey = $location.search().cosignerKey;
if ($scope.rentProcessId || $scope.cosignerKey) {
$scope.readOnly = false;
} else {
$scope.readOnly = true;
}
$scope.setTabIndex = function(index) {
$scope.tabIndex = index;
}
$scope.fileChanged = function(kind, file) {
var reader = new FileReader();
reader.onload = function(e) {
if (kind == 'front') {
$scope.frontIdFile = file;
$scope.frontIdImage = e.target.result;
$scope.$apply();
} else {
$scope.backIdFile = file;
$scope.backIdImage = e.target.result;
$scope.$apply();
}
};
reader.readAsDataURL(file.files[0]);
$scope.$apply();
}
$scope.uploadForm = function() {
var params = {};
if ($scope.insuranceStudyContactInfo.city) {
$scope.insuranceStudyContactInfo.cityCode = $scope.insuranceStudyContactInfo.city.cityCode;
}
if ($scope.insuranceStudyJobInfo.city) {
$scope.insuranceStudyJobInfo.cityCode = $scope.insuranceStudyJobInfo.city.cityCode;
}
if ($scope.insuranceStudyAssets.hasProperties) {
if ($scope.insuranceStudyAssets.property1 && $scope.insuranceStudyAssets.property1.city) {
$scope.insuranceStudyAssets.property1.cityCode = $scope.insuranceStudyAssets.property1.city.cityCode || null;
} else {
delete $scope.insuranceStudyAssets.property1;
}
if ($scope.insuranceStudyAssets.property2 && $scope.insuranceStudyAssets.property2.city) {
$scope.insuranceStudyAssets.property2.cityCode = $scope.insuranceStudyAssets.property2.city.cityCode || null;
} else {
delete $scope.insuranceStudyAssets.property2;
}
} else {
delete $scope.insuranceStudyAssets.property1;
delete $scope.insuranceStudyAssets.property2;
}
if ($scope.propertyListing.rentProcessId) {
params.rentProcessId = $scope.propertyListing.rentProcessId;
}
if ($location.search().cosignerKey) {
params.cosignerKey = $location.search().cosignerKey;
}
if ($scope.identityInfo.date) {
$scope.identityInfo.birthDate = formatedDate($scope.identityInfo.date, 'DD/MM/YYYY');
}
$scope.insuranceStudyFinancialInfo.doImport = $scope.insuranceStudyFinancialInfo.doImport || false;
$scope.insuranceStudyFinancialInfo.doExport = $scope.insuranceStudyFinancialInfo.doExport || false;
$scope.insuranceStudyFinancialInfo.doInvest = $scope.insuranceStudyFinancialInfo.doInvest || false;
$scope.insuranceStudyFinancialInfo.doCurrencyExchange = $scope.insuranceStudyFinancialInfo.doCurrencyExchange || false;
$scope.insuranceStudyFinancialInfo.doPayServices = $scope.insuranceStudyFinancialInfo.doPayServices || false;
$scope.insuranceStudyFinancialInfo.doPayLoans = $scope.insuranceStudyFinancialInfo.doPayLoans || false;
$scope.insuranceStudyFinancialInfo.doTransactions = $scope.insuranceStudyFinancialInfo.doTransactions || false;
params.isCorporation = $scope.isCorporation;
params.contactInfo = JSON.stringify($scope.insuranceStudyContactInfo);
params.jobInfo = JSON.stringify($scope.insuranceStudyJobInfo);
params.financialInfo = JSON.stringify($scope.insuranceStudyFinancialInfo);
params.assets = JSON.stringify($scope.insuranceStudyAssets);
params.virtualSignatureInfo = JSON.stringify($scope.virtualSignatureInfo);
params.identityInfo = JSON.stringify($scope.identityInfo);
$scope.isReadOnly = function() {
if ($scope.readOnly) {
$http.get(root + "Insurance/s/getInsuranceRequest", {
params: {
insuranceRequestId: $scope.propertyListing.insuranceRequestId
}
}).then(function(res) {
$scope.code = res.data.code;
$scope.type = res.data.type;
$scope.datetime = res.data.datetime;
$scope.status = res.data.status;
$scope.listingCode = res.data.listingCode;
$scope.isCorporation = res.data.corporation + "";
$scope.identityInfo.documentTypeCode = res.data.identityInfo.documentTypeCode;
$scope.identityInfo.documentNumber = res.data.identityInfo.documentNumber;
$scope.identityInfo.names = res.data.identityInfo.names;
$scope.identityInfo.lastNames = res.data.identityInfo.lastNames;
$scope.identityInfo.date = res.data.identityInfo.birthDate;
$scope.insuranceStudyContactInfo = res.data.contactInfo;
$scope.insuranceStudyJobInfo = res.data.jobInfo;
$scope.insuranceStudyFinancialInfo = res.data.financialInfo;
if ($scope.insuranceStudyFinancialInfo.foreignAccountBank) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccount) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCurrency) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCountry) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCity) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.doImport) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doExport) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doInvest) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doCurrencyExchange) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doPayServices) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doPayLoans) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doTransactions) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
$scope.insuranceStudyAssets = res.data.assets;
if ($scope.insuranceStudyAssets.property1 || $scope.insuranceStudyAssets.property2) {
$scope.insuranceStudyAssets.hasProperties = true;
}
if ($scope.insuranceStudyAssets.vehicle1 || $scope.insuranceStudyAssets.vehicle2) {
$scope.insuranceStudyAssets.hasCars = true;
}
$scope.availableActions = res.data.availableActions;
});
}
}
$scope.isReadOnly();
}]);
That error says your are using an unknown dependency in your controller.
Here, the error says that the "unknown dependency" is a provider called $element.
! There are 3 types of providers in angularjs: service, factory or provider
2 reasons why you can have this problem:
1) If you don't have any providers (service, factory or provider) called $element in your project you shouldn't have a dependency for it.
In IdentityVerificationWizardCtrl
Instead of:
.controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', '$element', function($scope, upload, $http, listing, $routeParams, $location, Dialogs, $element)
Write:
.controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', function($scope, upload, $http, listing, $routeParams, $location, Dialog)
2) if you have a provider called $element , maybe you didn't call it into your index.html
PS: In angularjs, $element is a parametter used into the link function and refer to the DOM element. So IMO opinion your error is because of reason 1

How do I pre-cache url content in ionic 1/angular 1?

I am pretty new to ionic and working on an app where you load a bunch of categories ,followed by a list of items in the category and when you click on the item in the category a documenturl loads containing the content which is basically an image. Currently, everything loads fine, but I would like to preload the content the moment my category is visible, so even if I go offline I should be able to click on any of the items within the category list and load the respective document. I looked online but I couldn't find anything except localstorage which caches data after you have visited it and not before. Is there a way I can pre-load or pre-cache content ?
Here's my code for controllers:
angular.module('starter.controllers', ["utility.services"])
.directive("bindCompiledHtml", ["$compile", "zoomPerOrientation", function($compile, zoomPerOrientation) {
return {
template: '<div></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;
var newElem = $compile(value)(scope.$parent);
elem.contents().remove();
zoomPerOrientation.zoomTo('docScroll');
elem.append(newElem);
elem.bind("click", function(e) {
e.stopPropagation();
e.preventDefault();
if (e.target.tagName === 'A') {
window.open(encodeURI(e.target.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
} else if (e.target.parentNode.tagName === 'A') {
window.open(encodeURI(e.target.parentNode.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
}
});
});
}
};
}])
.directive('setHeight', function($window) {
return {
link: function(scope, element, attrs) {
element.css('height', $window.innerHeight + 30);
}
}
})
.controller("MenuCtrl", ["$scope", "MenuService", "$stateParams", "$state", "ConfigUrls", function($scope, MenuService, $stateParams, $state, ConfigUrls) {
// debugger;
console.log("MenuCtrl");
$scope.menuData = [];
$scope.noMenuDataMsg = "Loading....";
$scope.LoadMenu = function(forceLoad) {
console.log("MenuCtrl - LoadMenu");
// console.log(MenuService.getClinicalAreas(forceLoad));
MenuService.getClinicalAreas(forceLoad).then(function(data) {
$scope.menuData = data;
}, function(err) {
console.log(err);
if (err.error === "timeout") {
$scope.noMenuDataMsg = "Error: Unable to retrieve data due to network error! Please try again when you are in network."
} else {
$scope.noMenuDataMsg = "Error retrieving data! Please contact system administrator."
}
$scope.menuData = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.deviceModel = window.localStorage.getItem("deviceModel");
// console.log(MenuService);
// console.log($scope.menuData);
$scope.title = $stateParams.topTitle;
var metaTag = $stateParams.metaTag;
//console.log(ConfigUrls[metaTag+"Published"]);
if (metaTag !== "") {
window.localStorage.setItem('publishedUrl', ConfigUrls[metaTag + "Published"]);
window.localStorage.setItem('docUrl', ConfigUrls[metaTag + "DocUrl"]);
window.localStorage.setItem('cacheKeyPrefix', metaTag);
$scope.LoadMenu(false);
} else {
$scope.noMenuDataMsg = "Under Construction!";
}
//console.log("metaTag",metaTag);
//if ($stateParams.topTitle === "Transplant") {
// $scope.LoadMenu(false);
//}
//else {
// $scope.noMenuDataMsg = "Under Construction!";
//}
$scope.showHomeItem = function(clinicalArea) {
console.log("MenuCtrl - showHomeItem");
$state.go('contr.home', {
cA: clinicalArea
});
}
$scope.goHome = function() {
console.log("MenuCtrl - goHome");
$state.go('contr.topmenu');
}
}])
.controller("HomeCtrl", ["$scope", "HomeService", "$stateParams", "$state", function($scope, HomeService, $stateParams, $state) {
console.log("HomeCtrl");
$scope.organs = [];
$scope.title = $stateParams.cA;
$scope.LoadHome = function(forceLoad) {
console.log("HomeCtrl - LoadHome");
HomeService.getOrgans($stateParams.cA, forceLoad).then(function(data) {
$scope.organs = data;
}, function(err) {
$scope.organs = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.showLevel2Item = function(title, clinicalArea) {
console.log("HomeCtrl - showLevel2Item");
$state.go('contr.level2', {
title: title,
cA: clinicalArea
});
//:title/:cA
}
$scope.goHome = function() {
console.log("HomeCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadHome(false);
}])
.controller('Level2Ctrl', ["$scope", "OrganService", "$stateParams", "$state", function($scope, OrganService, $stateParams, $state) {
$scope.title = "Level2 ";
console.log("Level2Ctrl");
$scope.parentOrgan = {};
$scope.viewTitle = $stateParams.title;
OrganService.getSingleOrganDetail($stateParams.cA, $stateParams.title).then(function(data) {
$scope.parentOrgan = data[0];
$scope.parentOrgan.clinicalAreaDisp = "Transplant";
}, function(err) {
$scope.parentOrgan = {};
});
console.log($scope.parentOrgan);
$scope.subGroup = [];
$scope.LoadSubGroups = function(forceLoad) {
console.log("Level2Ctrl - LoadSubGroups");
OrganService.getSubGroups($stateParams.title, $stateParams.cA, forceLoad).then(function(data) {
$scope.subGroup = data;
console.log("$scope.subGroup", $scope.subGroup);
}, function(err) {
$scope.subGroup = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
//$scope.deviceModel = window.localStorage.getItem("deviceModel");
//$scope.devicePlatform = window.localStorage.getItem("devicePlatform");
$scope.toggleGroup = function(group) {
group.show = !group.show;
};
$scope.isGroupShown = function(group) {
return group.show;
};
$scope.showDocumentDtl = function(id, docTitle, sgName, mnGroup, area) {
console.log("Level2Ctrl - showDocumentDtl");
$state.go('contr.doc-dtl', {
id: id,
docTitle: docTitle,
sgName: sgName,
mnGroup: mnGroup,
area: area
});
//:title/:cA
}
$scope.goHome = function() {
console.log("Level2Ctrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadSubGroups();
}])
.controller('DocumentCtrl', ["$scope", "DocmentService", "zoomPerOrientation", "$stateParams", "$ionicScrollDelegate", "$state", function($scope, DocmentService, zoomPerOrientation, $stateParams, $ionicScrollDelegate, $state) {
$scope.viewData = {};
$scope.snippet = "<p style='margin-top:40%;margin-left:40%;font-weight:bold;font-size:1.6em;' class='item item-stable'>Loading...</p>";
$scope.statusMessage = "";
$scope.title = $stateParams.mnGroup;
console.log("DocumentCtrl");
console.log("$stateParams", $stateParams);
//, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area
// console.log("Inside docuemtn controller");
$scope.LoadDocument = function(forceLoad) {
console.log("DocumentCtrl - LoadDocument");
DocmentService.getRowDocument($stateParams.id, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area, forceLoad).then(
function(data) {
// console.log("successfull", data);
$scope.viewData = data;
$scope.snippet = $scope.viewData.document;
},
function(reason) {
// console.log("Error Occured", reason);
$scope.viewData = {
"docTitle": "Error Occured!"
};
if (reason.error === "timeout") {
$scope.snippet = "<div style='margin-top:40%;margin-left:15%;font-weight:bold;font-size:1.6em;width:600px !important;padding:16px !important;line-height:120%;' class='item item-stable item-text-wrap item-complex'>Error: Unable to the load the document at this time. Please make sure you are in the network or you have already fetched the document while you were in the network!</div>";
}
// $scope.statusMessage = err;
}).finally(function() {
console.log("finally", data);
$scope.$broadcast('scroll.refreshComplete');
});
}
//below code would be refactored in near future.
//It is not a good practice adding window event listener in the controller
window.addEventListener('orientationchange', function() {
try {
if ($ionicScrollDelegate.$getByHandle('docScroll')._instances.length > 2) {
zoomPerOrientation.zoomTo('docScroll');
}
} catch (exception) {
console.log(exception);
}
});
$scope.goHome = function() {
console.log("DocumentCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadDocument(true);
}])
.controller('TopMenuCtrl', ["$scope", "TopMenuService", "$state", "$ionicHistory",
function($scope, TopMenuService, $state, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.title = "Rules";
$scope.menuItems = [];
$scope.menuItemsLandscape = [];
$scope.flatMenuItems = [];
$scope.tileView = true;
$scope.listView = false;
$scope.portraitMode = true;
console.log("TopMenuCtrl");
TopMenuService.getMenuItems().then(function(data) {
$scope.menuItems = data.colData;
$scope.flatMenuItems = data.flatData;
$scope.menuItemsLandscape = data.threeColData;
console.log($scope.menuItems);
},
function() {
$scope.menuItems = [];
});
$scope.showMenuItem = function(title, metaTag) {
console.log("TopMenuCtrl - showMenuItem");
//$state.go('tab.menu', { topTitle: title });
$state.go('contr.menu', {
topTitle: title,
metaTag: metaTag
});
}
$scope.itemChanged = function() {
console.log("TopMenuCtrl - itemChanged");
console.log($scope.tileView);
if ($scope.tileView) {
$scope.listView = true;
$scope.tileView = false;
} else {
$scope.listView = false;
$scope.tileView = true;
}
}
// console.log(window.orientation);
function onChangeOrientation() {
console.log("TopMenuCtrl - onChangeOrientation");
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.portraitMode = false;
}
//portrait
else {
$scope.portraitMode = true;
}
} catch (exception) {
console.log(exception);
}
}
onChangeOrientation();
window.addEventListener('orientationchange', function() {
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.$apply(function() {
$scope.portraitMode = false;
});
}
//portrait
else {
$scope.$apply(function() {
$scope.portraitMode = true;
});
}
} catch (exception) {
console.log(exception);
}
});
}
])
.controller('LoginController', ["$scope", "$location", "$ionicHistory", '$timeout', '$ionicLoading', '$state',
function($scope, $location, $ionicHistory, $timeout, $ionicLoading, $state) {
$scope.username = "Guest";
$scope.password = "Abcd123";
// $ionicNavBarDelegate.showBar(false);
$scope.login = function(password) {
console.log("LoginController - login");
if (password) {
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
template: '<p class="item-icon-left bar-header"><ion-spinner icon="lines"/></p>',
maxWidth: 200,
showDelay: 0
});
window.localStorage.setItem("Pswd", password);
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$timeout(function() {
$ionicLoading.hide();
//$location.path("/tab/topmenu");
$state.go('contr.topmenu');
}, 1000);
}
}
}
])
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
Please let me know if you need any other info.Also, currently I do support local cache to cache categories locally, but not pre-cached. Is there a way to retrieve these documents beforehand? Please check my loaddocuments section which deals with loading document url's once you click on the specific item.
Please refer this I've already explained everything with programming approach.
StackOverflow Solution Link
You can use this explained approach, and adding for others who are looking for answer to this question.

AngularJS share data bettween parent and child scope directives

I have a widget like directive called waComments, it loads components via a RESTful service and displays them. In my view I'm using ng-repeat to loop over them and to render them with a button that if pressed Shows a new reply to form. This his handled by the waCommentsReply directive. One waComments widget has many child directives of type waCommentsReply. When the form is filled and submitted I want to add the new comment on top of my comments list. So both directives have to share the comments data.
I've tried to implement this here Sharing data between directives but without much success, the comment data is not updated when I add a new comment. I see that the RESTful API calls work and the data is returned, so this is not an issue.
Why is my implementation of Sharing data between directives not working in my case?
waCommentsReply directive:
waFrontend.directive('waCommentsReply', ['$rootScope', 'Comment', 'WaFormValidation', 'WaCommentStore', function($rootScope, Comment, WaFormValidation, WaCommentStore) {
return {
restrict: 'E',
templateUrl: '/stubs/comment-form.html',
transclude: true,
scope: {
replyTo: '#replyTo',
replyFormList: '=replyFormList',
loggedIn: '#loggedIn',
model: '#model',
id: '#id',
cancelButton: '#cancelButton'
},
controller: function($scope) {
$scope.comments = WaCommentStore;
if ($scope.cancelButton == undefined) {
$scope.cancelButton = true;
} else {
$scope.cancelButton = false;
}
$scope.comment = $scope.commentForm = {
Comment: {
author_name: '',
body: '',
model: $scope.model,
foreign_key: $scope.id,
parent_id: $scope.replyTo
}
};
$scope.$watch('replyFormList', function (newValue, oldValue) {
if (newValue) {
$scope.replyFormList = newValue;
}
});
if ($scope.loggedIn == undefined) {
$scope.loggedIn = false;
}
/**
* Handles the submission and response of a reply
*
* #return void
*/
$scope.reply = function() {
Comment.add($scope.comment).then(function(result) {
if (result.status == 'fail' || result.validation != undefined) {
$scope.validationErrors = result.validation;
WaFormValidation.validate(result.validation, $scope.commentForm);
} else if (result.status == 'success') {
//$scope.$parent.comments.unshift(result.data.comment);
//$scope.comments.unshift(result.data.comment);
$scope.comments.comments.unshift(result.data.comment);
//WaCommentStore.append($scope.model, $scope.id, result.data.comment);
$scope.comments, $scope.id, result.data.comment
$scope.comment = {};
$scope.replyFormList[$scope.replyTo] = false;
}
});
};
$scope.close = function() {
$scope.comment = {};
if ($scope.replyFormList[$scope.replyTo] != undefined) {
$scope.replyFormList[$scope.replyTo] = false;
}
}
}
};
}]);
WaCommentStore directive:
waFrontend.factory('WaCommentStore', function() {
return {
comments: []
};
});
waComments directive:
waFrontend.directive('waComments', ['$rootScope', 'Comment', 'WaCommentStore', function($rootScope, Comment, WaCommentStore) {
return {
restrict: 'E',
templateUrl: '/stubs/comments.html',
scope: {
model: '#commentModel',
id: '#commentFk'
},
controller: function($scope) {
$scope.comments = WaCommentStore;
$scope.loaded = false;
$scope.loadedMore = true;
$scope.currentPage = 1;
$scope.loggedIn = false;
$scope.paging = {};
$scope.replyFormList = {};
Comment.comments($scope.model, $scope.id).then(function(result) {
$scope.comments.comments.push.apply($scope.comments.comments, result.data.comments);
$scope.loggedIn = result.data.loggedIn;
$scope.paging = result.paging.Comment;
$scope.loaded = true;
});
$scope.loadMore = function() {
$scope.loadedMore = false;
if ($scope.paging.nextPage == false) {
//return false;
}
var options = {
page: $scope.paging.page + 1
};
Comment.comments($scope.model, $scope.id, options).then(function(result) {
$scope.comments.comments.push.apply($scope.comments.comments, result.data.comments);
$scope.paging = result.paging.Comment;
$scope.loadedMore = true;
});
};
$scope.submitComment = function() {
//alert($scope.author_name + $scope.body);
};
$scope.reply = function(replyId) {
$scope.replyFormList[replyId] = true;
}
}
};
}]);
since in both directive you defined scope: {} basically it means you defined those directives to use isolated scope.
with isolated scope, a scope/directive can't see what is in the parent scope.
however parent scope, can be affected by the child scope changes with 2 way binding definition.
https://docs.angularjs.org/guide/scope
try changing the shared data like this
waFrontend.factory('WaCommentStore', function() {
var comments = [];
var getComments = function() { return comments; }
var setComments = function(data) { comments = data; }
return {
getComments : getComments ,
setComments : setComments
};
});
I wanted to put it as a comments, but it would have been difficult to understand for you.
Please let me know if this works, else I will delete this answer.

why ng-click not working?

I write a directive to impl ng-disabled because i just can use angularjs which version is 1.1.5,it't not provide ng-disabled,so
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
}
};
});
the html code:
<html ng-app="tableApp">
<head></head>
<body>
<div ng-controller="TableCtrl">
<input ng-model="page"/>
<button class="btn btn-primary" ng-click="previouspage()" my-disabled="page <=1">上一页</button>
</div>
</body>
</html>
but why i click this button,it can't call the function previouspage()
this is my angularjs code
var tableApp = angular.module('tableApp', [], function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded;charset=utf-8';
});
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
$compile(attrs);
}
};
});
tableApp.controller('TableCtrl', function ($scope, $http) {
$scope.page = 1;
$scope.getCr = function getCr(later) {
var url = '/cms/copyright/find';
var request = $http({
method: 'get',
url: url,
params: {
page_length: 25,
start: ($scope.page - 1) * 25,
s: ''
}
});
request.then(function (data) {
if (data.data.result == 'OK') {
console.log(data.data);
$scope.copyright = data.data;
if (later != undefined) {
later();
}
}
});
};
$scope.nextpage = function nextpage() {
$scope.page += 1;
$scope.getCr();
};
$scope.onepage = function onepage() {
$scope.page = 1;
$scope.getCr();
};
$scope.previouspage = function previouspage() {
$scope.page -= 1;
$scope.getCr();
};
$scope.setPos = function setPos(index, holder_id) {
var pos = window.prompt("请输入排序位置", $scope.copyright.items[index].pos);
console.log(pos);
if (pos != null && pos != "" && parseInt(pos) > 0) {
var a = 'holder_id=' + holder_id + '&pos=' + pos;
$http.post('/cms/copyright/top', a).then(function (data) {
data = data.data;
if (data.result == 'OK') {
$scope.getCr(function () {
$scope.copyright.items[index].change = true;
});
} else {
alert(data.result);
}
});
}
console.log($scope.copyright.items[index]);
};
$scope.getCr();
});
Your problem is related to $scope.
When you are explicitly creating an isolated scope in your directive (using scope: {}) you can't access parent scope directly. If you don't, there is no problem doing so.
So, in short, just change ng-click="previouspage()" to ng-click="$parent.previouspage()" inside your HTML template.
Related plunker here: http://plnkr.co/edit/WRflPF
You could also refactor your directive's link function and remove unnecessary properties. So directive could be:
app.directive('myDisabled', function () {
return {
restrict: 'A',
scope: {
myDisabled: '='
},
link: function(scope, element) {
scope.$watch('myDisabled', function (val) {
element.attr('disabled', val);
});
}
};
});
The problem is the directive scope. You try to access an scope variable from parent scope (your controllers scope)
If you disable the isolate scope for your directive it works
For example:
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
}
};
});

why angularjs directive inherit the scope but doesn't change the scope variable?

(function () {
'use strict'
var pagesize = 5;
var memberManager = angular.module('memberManager',['mydirective'],function ($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})
memberManager.constant('apiUri', {
getMembers: '/membermanage/get',
charge: '/membermanage/charge',
exchange: '/membermanage/exchange'
});
memberManager.factory('managerService',function ($http,apiUri) {
return {
getMembers: function (data) {
return $http.get(apiUri.getMembers,{ params: data });
},
charge: function (data) {
return $http.post(apiUri.charge,data);
},
exchange: function (data) {
return $http.post(apiUri.exchange,data);
}
}
});
memberManager.directive('modalWin',function () {
return {
restrict: 'A',
link: function (scope,elem,attrs) {
var modalWinId = attrs.targetid;
var clickHandler = function () {
var index = $(elem).attr('index');
scope.$apply(function () {
scope.itemIndex = parseInt(index);
scope.chargeModel.index = parseInt(index);
});
$('#' + modalWinId).modal();
scope.$on('http:cash',function () {
$('#' + modalWinId).modal('hide');
});
scope.$on('http:exchange',function () {
$('#' + modalWinId).modal('hide');
});
};
$(elem).bind('click',clickHandler);
}
}
})
memberManager.controller('manCtrl',function ($scope,managerService,$rootScope,managerHelper) {
$scope.isLoadingData = true;
$scope.chargeModel = {
index: 0,
cash_num: 0,
cash_store: '',
cash_stuff: ''
};
// which item to be edit?
$scope.itemIndex = 0;
$scope.test = {
index: 0
};
$scope.exchangeModel = {
exchange_number: 0,
exchange_way: 1,// 直接消费
exchange_store: '',
exchange_pass: ''
}
$scope.loader = {
exchange: false,
cash: false
};
$scope.exchange = function () {
alert($scope.itemIndex);
$scope.loader.exchange = true;
var data = {
exchange_number: $scope.exchangeModel.exchange_number,
exchange_wechat_id: $scope.model[$scope.itemIndex].wc_openid,
exchange_type: $scope.exchangeModel.exchange_type
};
console.log(data);
managerService.exchange(data).success(function (data) {
$scope.loader.exchange = false;
$rootScope.$broadcast('http:exchange');
$scope.getData($scope.currentPageIndex);
})
};
})();
Click event callbacks execute outside Angular world. You need to use $apply:
demo.directive('testD',function(){
return {
restrict: 'A',
link: function(scope,elem,attr){
$(elem).click(function(){
scope.$apply(function(){
scope.val = 5;
});
});
}
}
});
Fiddle
Try this :
var demo = angular('demo',[]);
demo.directive('testD',function(){
restrict: 'A',
scope: {
'val': '=' // here the fix
},
link: function(scope,elem,attr){
$(elem).click(function(){
scope.val = 5;
});
}
});
demo.controller('testCtrl',function($scope){
$scope.val = 0;
});

Categories