I'm trying to get md-autocomplete to play nice with Algolia's Angular service. I'm stuck on getting the dropdown to display the results being returned from Algolia. The content is in console yet the dropdown will not populate with the updated results. What am I missing?
tl;dr: Plnkr
"Backend"
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl ($timeout, $q, $log, algolia, $http, $scope) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
// Algolia demo keys below
var client = algolia.Client('latency', '6be0576ff61c053d5f9a3225e2a90f76');
var index = client.initIndex('contacts');
$scope.query = '';
$scope.hits = [];
// Disable cache
$scope.noCacheResults = false;
// ******************************
// Internal methods
// ******************************
/**
* Search for repos... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
// This returns objects in console
var results = self.algoliaSearch(query);
// This returns: TypeError: Cannot read property 'then' of undefined
// var results = query ? self.algoliaSearch( createFilterFor(query) ) : self.repos, deferred;
return results;
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `components` list of key/value pairs
*/
function algoliaSearch(text) {
try {
index
.search(text)
.then(function(content) {
// if (content.query !== $scope.query) {
// // do not take out-dated answers into account
// return;
// }
$scope.hits = content.hits;
return content.hits.map( function (hit) {
hit.value = hit.name.toLowerCase();
$log.debug(hit);
return hit;
});
}, function(content) {
console.log('Error: ' + content.message);
});
} catch(e) {
$log.debug(e);
}
}
function loadAll() {
var repos = [
{
'name' : 'Angular 1',
'url' : 'https://github.com/angular/angular.js',
'watchers' : '3,623',
'forks' : '16,175',
}
];
return repos.map( function (repo) {
repo.value = repo.name.toLowerCase();
return repo;
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
"Frontend"
<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak>
<md-content layout-padding layout="column">
<form ng-submit="$event.preventDefault()">
<p>Use <code><md-autocomplete></code> with custom templates to show styled autocomplete results.</p>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="ctrl.noCacheResults"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.name"
md-min-length="0"
placeholder="Pick an Angular repository"
md-menu-class="autocomplete-custom-template">
<md-item-template>
{{item}}
<span class="item-title">
<md-icon md-svg-icon="img/icons/octicon-repo.svg"></md-icon>
<span> {{item.name}} </span>
</span>
<span class="item-metadata">
<span class="item-metastat">
<strong>{{item.watchers}}</strong> watchers
</span>
<span class="item-metastat">
<strong>{{item.forks}}</strong> forks
</span>
</span>
</md-item-template>
</md-autocomplete>
</form>
</md-content>
</div>
"Algolia default"
<section class="panel">
<header class="panel-heading">
<div class="search_box">
<form action="#" method="get">
<input autocomplete="off" class="autocomplete" placeholder="Start typing" type="text" spellcheck="false" id="q" ng-model="query" />
<div class="searchbutton">
<i class="icon-search icon-large"></i>
</div>
</form>
</div>
</header>
</section>
<h1>Results</h1>
<div class="hit" ng-repeat="hit in hits">
<div class="attribute" ng-repeat="(attribute,v) in hit._highlightResult">
<span>{{ attribute }}: </span>
<span ng-bind-html="v.value"></span>
</div>
</div>
<script type="text/javascript">
angular
.module('myapp', ['algoliasearch', 'ngSanitize'])
.controller('SearchCtrl', ['$scope', 'algolia', function($scope, algolia) {
$scope.query = '';
$scope.hits = [];
// Replace the following values by your ApplicationID and ApiKey.
var client = algolia.Client('latency', '6be0576ff61c053d5f9a3225e2a90f76');
// Replace the following value by the name of the index you want to query.
var index = client.initIndex('contacts');
$scope.$watch('query', function() {
index.search($scope.query, { hitsPerPage: 5 }).then(function(content) {
if (content.query !== $scope.query) {
// do not take out-dated answers into account
return;
}
$scope.hits = content.hits;
}, function(content) {
console.log('Error: ' + content.message);
});
});
}]);
</script>
You should return a Promise since the call to AlgoliaSearch is asynchronous:
function querySearch(query) {
return algoliaSearch(query);
// var results = query ? self.algoliaSearch( createFilterFor(query) ) : self.repos, deferred;
}
You can find the updated code here: http://plnkr.co/edit/C8fmsNRzNsXEC7InNM6a
Related
I have an angularJS application. I have implemented a generic workflow using $routeProvider, templateUrl & Controllers.
Each step(screen) is verified when user click on next button and moves to the next step if validation passes. If validation fails user is required to fix all the error, displayed on the screen, before moving to next step.
When user has visited all the screens(passed validation for each screen) all the breadcrumbs get enabled and now user can move freely between those steps/breadcrumbs.
Requirement:
Now I want to allow user to move freely between steps by clicking on the breadcrumbs and when user clicks on the lodge button, on the last step, validation for current as well as for all previous steps should be invoked, and clicking on the error user should be able taken to the relevant step/screen.
Also I want to keep the functionality of validating the individual steps on the click of next button.
As you can see each screen has a separate controller along with the scope.
Once user move from one step to another it can't access the previous scope.
Initially I thought of storing scope of each screen in an array, but once I move between steps new scope is created (as it should) and only current step has a form with valid data model and "valid" flag as false.
Form object at current step
Form object of other screen without and fields attached
I'm not very well versed with Angularjs and trying to get some idea weather
Is it possible what I'm trying to achieve keeping the existing functionality intact. (My understanding is that I can't have a single controller since I need to keep the functionality of validating each step individually)?
Is there a better way to trying to achieve this functionality?
PS: Sadly I can't upgrade to newer version of Angular.
Any help will be highly appreciated.
Form Validation
validator.validate = function($scope, submitCallback, additionalOptions) {
var options = {};
$.extend(options, commonOptions, additionalOptions);
var form = $scope[options.formName];
hideErrorMessages(options.errorContainerSelectorId);
if (form.$valid) {
submitCallback();
return;
}
showErrorMessages({message: composeAngularValidationErrors(form),
errorContainer: $('#' + options.errorContainerSelectorId)});
};
View:
<#assign temp=JspTaglibs["http://www.test.com/tags"]>
<div ng-controller="LodgeApplicationWorkflowController" ng-cloak>
<workflow-breadcrumbs></workflow-breadcrumbs>
{{model | json}}
<div ng-view>
</div>
<script type="text/ng-template" id="applicant-details">
<form name="form" method="post" action="#" class="standard">
<h3>Primary contact details</h3>
<div class="row">
<div class="span3">
<label for="owner-primary-contact">Primary contact:</label>
<select class="span3" id="owner-primary-contact" required name="applicantDetails.primaryContact"
ng-model="model.applicantDetails.primaryContactId"
ng-options="user.id as user.fullName for user in refData.contactInfos"
>
<option value=""></option>
</select>
</div>
<div class="span3">
<label for="owner-primary-contact-phone">Phone:</label>
<input type="text" class="span3" id="owner-primary-contact-phone" name="applicantDetails.primaryContactPhone"
readonly
ng-model="model.applicantDetails.primaryContactPhone"/>
</div>
<div class="span3">
<label for="owner-primary-contact-email">Email:</label>
<input type="text" class="span3" id="owner-primary-contact-email" name="applicantDetails.primaryContactEmail"
readonly
ng-model="model.applicantDetails.primaryContactEmail"/>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="lgc-methodology">
<form name="form" method="post" action="#" class="standard">
<h3>Describe the Your Methodology</h3>
<div class="row">
<div class="span9">
<label for="methodology">Describe the methodology which you propose to employ:
</label>
<textarea class="span9" id="methodology" name="methodology"
rows="10"
ng-maxlength="4000"
ng-model="model.methodology" required>
</textarea>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="approval-details">
<form name="form" method="post" action="#" class="standard">
<div class="row" ng-if="model.approvalDetails.planningApprovalsObtained === 'true'">
<div class="span9">
<label for="planning-approvals-details">Approval details:</label>
<textarea class="span6" id="planning-approvals-details"
name="approvalDetails.planningApprovalDetails"
ng-if="model.approvalDetails.planningApprovalsObtained === 'true'"
required ng-maxlength="4000"
ng-model="model.approvalDetails.planningApprovalDetails"></textarea>
</div>
</div>
<div class="row" ng-if="model.approvalDetails.planningApprovalsObtained === 'false'">
<div class="span9">
<label for="planning-approvals-details">Reasons:</label>
<textarea class="span6" id="planning-approvals-details"
name="approvalDetails.planningApprovalDetails"
ng-if="model.approvalDetails.planningApprovalsObtained === 'false'"
required ng-maxlength="4000"
ng-model="model.approvalDetails.planningApprovalDetails"></textarea>
</div>
</div>
<div >
<div class="row" >
<div class="span9">
<label for="environment-approval-details">Approval details:</label>
<textarea class="span6" id="environment-approval-details"
name="approvalDetails.environmentApprovalDetails"
ng-maxlength="4000"
ng-required="model.approvalDetails.environmentApprovalsObtained === 'true'"
ng-model="model.approvalDetails.environmentApprovalDetails"></textarea>
</div>
</div>
<div class="row" ng-if="model.approvalDetails.environmentApprovalsObtained === 'false'">
<div class="span9">
<label for="environment-approval-details">Reasons:</label>
<textarea class="span6" id="environment-approval-details"
name="approvalDetails.environmentApprovalDetails"
ng-maxlength="4000"
ng-required="model.approvalDetails.environmentApprovalsObtained === 'false'"
ng-model="model.approvalDetails.environmentApprovalDetails"></textarea>
</div>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="confirmation">
<form id="form" method="post" name="form" action="#" class="standard">
<div class="row">
<div class="span9">
<span class="checkbox inline">
<label for="confirm-information">
<input type="checkbox" id="confirm-information" name="confirmInformation"
ng-model="model.Confirmed" required />
I confirm that all the details are correct
</label>
</span>
</div>
</div>
</form>
</script>
<div class="form-actions">
<input type="button" class="btn" value="Cancel" ng-click="cancel()"/>
<div class="pull-right btn-toolbar">
<input id="previous" type="button" class="btn" value="Previous"
ng-click="workflow.handlePrevious()" ng-show="!workflow.isFirstStep()" ng-cloak/>
<input id="save-and-close" type="button" class="btn" value="Save draft and close"
ng-show="model.canSaveDraftAndClose && !workflow.isLastStep()"
ng-click="saveDraftAndClose()" ng-cloak/>
<input id="submit" type="button" class="btn btn-primary" value="{{workflow.getNextLabel()}}"
ng-disabled="!workflow.canNavigateToNextStep()"
ng-click="workflow.handleNext()" ng-cloak/>
</div>
</div>
</div>
Controllers:
angular.module('Test')
.config(function ($routeProvider) {
$routeProvider
.when('/applicant-details', {
templateUrl: 'applicant-details',
controller: 'ApplicantDetailsController'
})
.when('/methodology', {
templateUrl: 'methodology',
controller: 'MethodologyController'
})
.when('/approval-details', {
templateUrl: 'approval-details',
controller: 'ApprovalDetailsController'
})
.when('/confirmation', {
templateUrl: 'confirmation',
controller: 'ConfirmationController'
})
.otherwise({redirectTo: '/applicant-details'});
})
;
function LodgeApplicationWorkflowController( $scope, ctx, workflow, workflowModel, server, navigation) {
workflow.setSteps([
{
name: 'Applicant details',
path: 'applicant-details',
validationUrl: '/some url'
},
{
name: 'Methodology',
path: 'methodology'
},
{
name: 'Approval details',
path: 'approval-details'
},
{
name: 'Confirmation',
path: 'confirmation',
nextButtonLabel: 'Lodge',
onSubmit: function () {
disable('submit');
$scope.model.lodgeApplication = JSON.stringify($scope.model);
server.post({
url: ctx + '/some url' ,
json: JSON.stringify($scope.model),
successHandler: function () {
},
completeHandler: function () {
enable('submit');
},
validationErrorTitle: 'The request could not be completed because of the following issues:'
});
}
}
]);
function postInit() {
// To DO
}
function loadLodgement() {
// To DO
}
$scope.workflow = workflow;
$scope.model = workflowModel.model();
$scope.refData = workflowModel.refData();
$scope.accountDetails = {};
$scope.userDetails = {};
$scope.model.canSaveDraftAndClose = true;
server.getReferenceData([
'/URL1'
], function onAllReferenceDataRetrieved(data) {
$scope.$apply(function() {
$scope.refData.fuelSourceOptions = data[0];
$scope.refData.contactInfos = data[1].result;
$scope.refData.address = data[2];
$scope.refData.yearOptions = data[3];
$scope.refData.nmiNetworkOptions = data[4];
});
loadLodgement();
loadDraft();
});
$scope.saveDraftAndClose = function () {
var command = {};
server.post({
url: ctx + '/URL',
json: JSON.stringify(command),
successHandler: function (data) {
},
validationErrorTitle: 'The request could not be completed because of the following issues:'
});
};
$scope.cancel = function() {
navigation.to('Some URL');
};
}
function ApplicantDetailsController($scope, workflow, workflowModel, addressService, applicantServiceFactory) {
var applicantService = applicantServiceFactory();
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.applicantDetails = _.extend({
owner: { address: {} },
operator: { address: {} }
}, $scope.model.applicantDetails);
addressService.initialiseAddress($scope.model.applicantDetails);
}
function MethodologyController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
// Do something
}
function ApprovalDetailsController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.approvalDetails = $scope.model.approvalDetails || {};
// Do something
}
function ConfirmationController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.confirmation = { owner: {}, operator: {} };
$scope.model.confirmationConfirmed = false;
// Do something
}
WorkFlow
angular.module('Test')
.service('workflowModel', function() {
var refData = {};
var workflowModel = {};
return {
reset: function() {
workflowModel = {};
},
get : function(fragmentName) {
if (!workflowModel[fragmentName]) {
workflowModel[fragmentName] = {};
}
return workflowModel[fragmentName];
},
model : function(newWorkflowModel) {
if (newWorkflowModel) {
workflowModel = newWorkflowModel;
} else {
return workflowModel;
}
},
refData : function() {
return refData;
},
toJSON: function() {
return JSON.stringify(workflowModel);
}
};
})
.directive('workflowBreadcrumbs', function() {
return {
restrict: 'E',
template: '<ul class="breadcrumb">' +
'<li ng-class="{\'active\': workflow.currentStepPathIs(\'{{step.path}}\')}" ng-repeat="step in workflow.configuredSteps" ng-cloak>' +
'{{step.name}}<span ng-if="!workflow.visitedStep(step.path)">{{step.name}}</span><span class="divider" ng-if="!$last">/</span>' +
'</li>' +
'</ul>',
transclude: true
};
})
.factory('workflow', function ($rootScope, $location, server, validator, workflowModel, $timeout) {
function getStepByPath(configuredSteps, stepPath) {
return _.find(configuredSteps, function(step) { return step.path === stepPath; });
}
function validateServerSide(currentStep, callback) {
if (currentStep.validationUrl) {
server.post({
url: ctx + currentStep.validationUrl,
json : JSON.stringify(workflowModel.model()),
successHandler : function() {
$rootScope.$apply(function() {
callback();
});
}
});
} else {
callback();
}
}
function navigateNext(configuredSteps, currentStep) {
var currentStepIndex = _.indexOf(configuredSteps, currentStep);
navigateTo(configuredSteps[currentStepIndex + 1]);
}
function navigateTo(step) {
$location.path(step.path);
}
return {
setCurrentScope: function(scope) {
this.currentScope = scope;
this.firstStep = _.first(this.configuredSteps);
this.lastStep = _.last(this.configuredSteps);
this.currentStep = this.getCurrentStep();
if (!(this.currentStep === this.firstStep || this.hasEverVisitedSteps())) {
this.reset();
return false;
}
this.currentStep.visited = true;
hideErrorMessages();
this.focusOnFirstInputElementAndScrollToTop();
return true;
},
setSteps: function(steps) {
this.configuredSteps = steps;
},
focusOnFirstInputElementAndScrollToTop: function() {
$timeout(function() {
angular.element('select, input, textarea, button', '[ng-view]')
.filter(':visible')
.first()
.one('focus', scrollToTitle)
.focus();
scrollToTitle();
});
},
hasEverVisitedSteps: function() {
return _.find(this.configuredSteps, function(step) {
return step.visited;
}) !== undefined;
},
isFirstStep: function() {
return this.currentStep === this.firstStep;
},
isLastStep: function() {
return this.currentStep === this.lastStep;
},
currentStepPathIs: function(stepPath) {
return this.currentStep && stepPath === this.currentStep.path;
},
visitedStep: function(stepPath) {
return getStepByPath(this.configuredSteps, stepPath).visited;
},
getNextLabel: function() {
if (this.currentStep && this.currentStep.nextButtonLabel) {
return this.currentStep.nextButtonLabel;
}
return (this.isLastStep()) ? 'Submit' : 'Next';
},
handlePrevious: function() {
if (!this.isFirstStep()) {
var currentStepIndex = _.indexOf(this.configuredSteps, this.currentStep);
navigateTo(this.configuredSteps[currentStepIndex - 1]);
}
},
canNavigateToNextStep: function() {
return this.currentScope && (!this.currentScope.canSubmit || this.currentScope.canSubmit());
},
handleNext: function() {
var configuredSteps = this.configuredSteps;
var currentStep = this.currentStep;
if(this.isLastStep()) {
this.validateCurrentStep(this.currentStep.onSubmit);
} else {
this.validateCurrentStep(function() {
navigateNext(configuredSteps, currentStep);
});
}
},
validateCurrentStep: function(callback) {
var currentStep = this.currentStep;
if (this.currentScope.form) {
validator.validate(this.currentScope, function() {
validateServerSide(currentStep, callback);
});
} else {
validateServerSide(currentStep, callback);
}
},
getCurrentStep: function() {
return getStepByPath(this.configuredSteps, $location.path().substring(1));
},
reset: function() {
_.each(this.configuredSteps, function(step) { step.visited = false; });
this.firstStep.visited = true;
navigateTo(this.firstStep);
}
};
});
I've below requirement.
I've three controllers, ctrl 1, ctrl 2 and ctrl 3. I want to pass the value firstName to ctrl 1, lastName to ctrl2 and get the full name from ctrl3 using button click event.
I've tried my below code but I'm getting output as NaN.
Please help.
<script>
var myApp = angular.module('myApp', []);
myApp.factory('data', function () {
var factory = {};
var firstName = '';
var secondName = '';
factory.getName = function () {
return firstName + ' ' + secondName;
}
return factory;
});
myApp.controller('FirstController', function ($scope, data) {
$scope.firstName = data.firstName
});
myApp.controller('SecondController', function ($scope, data) {
$scope.secondName = data.secondName;
});
myApp.controller('ThirdController', function ($scope, data) {
$scope.getFullName = function () {
$scope.fullName = data.getName();
}
});
</script>
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="data.firstName">
<br>FirstName is : {{data.firstName}}
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="data.secondName">
<br>LastName is : {{data.secondName}}
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getFullName()">Get full Name</button>
Full name is: {{fullName}}
</div>
</div>
Try this method.
HTML:
<div ng-controller="BaseController">
<p>Base Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Base')">Update In Base</button>
<div ng-controller="DerivedController">
<p>Derived Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Derived')">Update In Derived</button>
</div>
</div>
JavaScript:
app.factory('sharedModel', function () {
// private stuff
var model = {
value: "initial Value"
};
// public API
return {
getValue: function() {
return model.value;
},
updateValue: function(value) {
model.value = value;
}
};
});
function BaseController($scope, sharedModel) {
$scope.model = sharedModel;
}
function DerivedController($scope, sharedModel) {
$scope.model = sharedModel;
}
WorkingFiddle.
Hope it helps!
Issues in your code snippet:
The service does not know about firstName and secondName properties.
data is not a $scope object in first and second controller.
No object allocation for the property in the service. "Save" button to bind to service.
var myApp = angular.module('myApp', []);
myApp.service('data', function () {
var service = {};
service.firstName = '';
service.secondName = '';
service.getName = function () {
return this.firstName + ' ' + this.secondName;
}
return service;
});
myApp.controller('FirstController', function ($scope, data) {
$scope.saveToService = function() {
data.firstName = $scope.firstName;
}
});
myApp.controller('SecondController', function ($scope, data) {
$scope.saveToService = function() {
data.secondName =$scope.secondName;
}
});
myApp.controller('ThirdController', function ($scope, data) {
$scope.getFullName = function () {
$scope.fullName = data.getName();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="firstName">
<button ng-click="saveToService()">Save</button>
<br>FirstName is : {{firstName}}
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="secondName">
<button ng-click="saveToService()">Save</button>
<br>LastName is : {{secondName}}
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getFullName()">Get full Name</button>
Full name is: {{fullName}}
</div>
</body>
I've been able to hook up angular materials autocomplete directive up to my data source and to display the information that I want, however I am unable to make the list of results display in the same way it does here:
https://material.angularjs.org/#/demo/material.components.autocomplete
My results appear like this:
http://i.imgur.com/3iMiXo5.png
Also, when I click away from the search box the autocomplete suggestions disappear and do not reappear on refocusing.
My HTML:
<div ng-controller="RoutesCtrl as ctrl" id="mainDiv" layout="column">
<div layout="row" flex>
<div layout="column" flex id="content">
<md-content>
<md-toolbar>
<div class="md-toolbar-tools header-color">
<md-button class="md-fab md-primary button-color" >
<md-icon class="ng-scope ng-isolate-scope md-default-theme hamburger-icon" aria-label="Menu" style="height: 14px; width: 14px;" md-svg-src="/assets/icons/ic_menu_18px.svg"></md-icon>
</md-button>
<md-button class="md-icon-button" aria-label="Settings"></md-button>
<h1 class="md-display-4"></h1>
</div>
</md-toolbar>
</md-content>
<md-content layout-padding layout="column">
<form ng-submit="$event.preventDefault()">
<md-autocomplete
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item="ctrl.selectedItem"
md-item-text="item.from_where + ' to ' + item.to_where"
placeholder="Search for a route"
md-no-cache="ctrl.noCache"
ng-disabled="ctrl.isDisabled"
md-min-length="3"
md-delay="0"
md-autoselect="true">
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.from_where + ' to ' + item.to_where}}</span>
</md-autocomplete>
</form>
</md-content>
<div ng-controller="MapController">
<leaflet center="center"></leaflet>
</div>
</div>
</div>
</div>
The html that mine generates does not have the ng-focus attribute or the class "ng-scope".
The service I am using to grab my data:
App.service('route', function route($http, $q){
var route = this;
route.routeList = {};
route.getAllRoutes = function(){
var defer = $q.defer();
$http.get('/routes')
.success(function(response){
route.routeList = response;
defer.resolve(response);
})
.error(function(error, status){
defer.reject(error);
});
return defer.promise;
};
return route;
});
And the controller:
App.controller("RoutesCtrl", function($scope, route, $timeout, $q, $log, $http){
$scope.init = function() {
$scope.getAll();
};
$scope.getAll = function(){
route.getAllRoutes()
.then(function(response){
//success
self.routes = response;
return route.routeList;
}, function(error) {
//error
}, function(message) {
//message
});
};
var self = this;
self.searchText = null;
self.querySearch = querySearch;
self.simulateQuery = true;
self.isDisabled = false;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.selectedItem = null;
function querySearch (q) {
var results = q ? self.routes.filter(createFilterFor(q) ) : [],
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function() { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange (text) {
$log.info('Text changed to ' + text);
}
function createFilterFor(query) {
var lowerCaseQuery = angular.lowercase(query);
return function FilterFn(route) {
return (route.route_from_to.toLowerCase().indexOf(lowerCaseQuery) === 0);
};
}
function selectedItemChange (item) {
if (!item) {
return
} else {
console.log(self.selectedItem);
$log.info('Item changed to ' + item.route_from_to);
}
}
$scope.init();
});
The problem was caused by angular-material 0.8.3. Updating to the latest release fixed it.
change attribute:
placeholder="Search for a route"
to
md-floating-label="Search for a route"
Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.
I have posted earlier this post with the choice of not providing all my code. But now im stuck since with the same problem so I give it a change with providing all my code.
I know its not easy to debug when the code is huge so I will try to explain precisely the problem.
Actually the problem is described in my precedent post so please read it and look at the code that is a simplification of this one.
But basically the problem is : I want to access $scope.data.comments from the $scope.deleteComment() function
As you see the code below you will notice that I have to add ng-controller="CommentController" twice for this to work.
If someone could explain why.. that would be great but I guess that is another question.
Thanks in advance for your help.
MAIN HTML
<div ng-init="loadComments('${params.username}', '${params.urlname}' )" ng-controller="CommentController">
<div ng-repeat="comments in data.comments" >
<div sdcomment param="comments" ></div>
</div>
</div>
APP
var soundshareApp = angular.module('soundshareApp', ['ngCookies']);
DIRECTIVES
soundshareApp.directive('sdcomment', ['$cookies', function($cookies){
var discussionId = null;
var found = false;
var username = $cookies.soundshare_username;
return {
restrict:'A',
scope: {
commentData: '=param'
},
templateUrl: '/js/views/comment/templates/commentList.html',
link : function(scope, element, attrs, controller) {
scope.$watch(element.children(), function(){
var children = element.children();
for(var i=0; i<children.length; i++){
if(children[i].nodeType !== 8){ //pas un commentaire <!-- -->
if( !found ){
found = true;
discussionId == scope.commentData.discussionId
}else if(found && discussionId == scope.commentData.discussionId){
angular.element(children[i]).removeClass('message-content');
angular.element(children[i]).addClass('answer-message-content');
}
if(found && discussionId != scope.commentData.discussionId){
discussionId = scope.commentData.discussionId
}
if(username == scope.commentData.username){
element.parent().bind('mouseover', function() {
// $(".delete-comment-button").show()
element.parent().find("span.delete-comment-button:first").attr('style', 'display: block !important');
});
element.parent().bind('mouseleave', function() {
element.parent().find("span.delete-comment-button:first").attr('style', 'none: block !important');
});
}
}
}
});
}
}
}]);
TEMPLATE
<div class="message-wrapper" ng-controller="CommentController">
<div class='message-content' ng-click="state.show = !state.show; setUsername(commentData.username)">
<img class='message-vignette' ng-src='{{commentData.avatarUrl}}'/>
<div class='message-username'>{{commentData.username}}</div>
<div class='project-message'>{{commentData.comment}}</div>
<div class='message-date'>{{commentData.dateCreated | date:'dd.MM.yyyy # hh:mm:ss' }}</div>
<div class="clearfix"></div>
</div>
<div ng-repeat="answer in answers" class="answer-message-content" >
<div class='message-content' ng-click="state.show = !state.show">
<img class='message-vignette' ng-src='{{answer.avatarUrl}}'/>
<div class='message-username'>{{answer.username}}</div>
<div class='project-message'> {{answer.comment}}</div>
<div class='message-date'>{{answer.dateCreated | date:'MM/dd/yyyy # h:mma' }}</div>
<div class="clearfix"></div>
</div>
</div>
<div class="add-comment-content show-hide" ng-show="state.show" >
<img class='message-vignette answer-message-vignette' ng-src='{{commentData.currentUserAvatarUrl}}'>
<div class="">
<form ng-submit="addComment(commentData)" id="commentForm-{{commentData.projectId}}">
<input id="input-comment-{{commentData.projectId}}" type="text" maxlength="" autofocus="autofocus" name="comment" placeholder="Write a comment..." ng-model="commentData.msg">
<input type="hidden" name="discussionId" value="{{commentData.discussionId}}" >
<input type="hidden" name="projectId" value="{{commentData.projectId}}" >
</form>
</div>
</div>
<span ng-click="deleteComment(commentData)" class="btn btn-default btn-xs delete-comment-button"><i class="icon-trash"></i></span>
</div>
CONTROLLER
'use strict';
soundshareApp.controller('CommentController', function($scope, $http) {
$scope.data = { comments : [] }
$scope.answers = [];
$scope.state = {}
$scope.project = { id : [] }
$scope.username = null;
$scope.loadComments = function(userName, urlName){
$http({
url: '/comment/by_project_id',
method: "GET",
params:
{
username: userName,
urlname: urlName
}
}).success(function(data) {
$scope.data.comments = data;
console.log($scope.data.comments);//WORKING
});;
}
$scope.addComment = function(commentData){
if("undefined" != commentData.msg){
commentData.msg = "#" + $scope.username + ": " + commentData.msg;
$http({
method : "POST",
url : "/comment/addAnswer",
params:
{
comment: commentData.msg,
discussionId: commentData.discussionId,
projectId:commentData.projectId
}
}).success(function(data){
$scope.answers.push(data);
$('.show-hide').hide();
$scope.commentData.msg = '';
});
}
}
$scope.setUsername = function(username){
$scope.username = username;
}
$scope.deleteComment = function ( comment ) {
console.log($scope.data.comments);//NOT WORKING
};
});