backbone with coffeescript router with id not working - backbone.js

I have Backbone App Here are codes :
This is Main.coffee :
require ["App/app","backbone"] ,(App,Backbone)->
app = new App()
Backbone.history.start()
This is app.coffee :
class AppRouter extends Backbone.Router
routes :
"" : 'Base'
"Browse/:id" : "Details"
initialize : ->
#render()
Browse : (id) ->
console.log "Hello"
stud = new Student({UserKey:id})
stud.fetch({
success :->
$('#content').html new View({model:stud}).el
})
null
This is my View.coffee
define ['jquery'
,'underscore'
,'backbone'
,'text!/Templates/Student/View.htm'] , ($ , _ , Backbone , ViewTemplate) ->
class StdView extends Backbone.View
#_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };
#template : _.template(View)
initialize : (options) ->
#render()
render :->
console.log #model.toJSON()
##setElement #template #model.toJSON()
#
And This is my View Template ( For showing details of student)
<input type="text" name="firstname" value="{{FirstName}}" placeholder="First Name" />
<input type="text" name="lastname" value="{{LastName}}" placeholder="Last Name" />
The items are rendered into a table with a link from where i click on edit buttton to get the details . Here is the template portion where the ids get rendered .
<td>
<a class="btn btn-small btn-inverse" href="#browse/{{UserKey}}"><i class="icon-edit icon-white"></i></a>
</td>
Now i have started the Backbone.history.start() . But no way its going to the Browse method which it should go if i click on link for example as : /browse/1 . Its not happening . The link which is rendered on the browser when i click is like this
http://localhost:40921/#browse/5
So where is it after all going wrong ???????

Routes are case sensitive, you should have this:
routes :
"" : 'Base'
"browse/:id" : "Details"
if you want #browse/5 to do anything. Or keep your routes as they are now and change your link to use #Browse/5.
Demo: http://jsfiddle.net/ambiguous/NLzyS/
If you want a case insensitive route, you could add a regex route manually using route:
initialize: ->
#route(/browse\/(\d+)/i, 'Details')
Demo: http://jsfiddle.net/ambiguous/2S6wr/

Related

How do I add value to my ligthning input using aura:iteration during onChange event of text box

Hi I'm new to salesforce. I'm trying to develop a lightning component that will take user input, process that input & will display the value in two text box.My lightning component looks like
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable" access="global" controller="VisionController">
<!--Remember to define your binding attribute-->
<aura:attribute name="val" type="String"/>
<lightning:card title="Partner Information">
<div class="slds-p-around_medium">
<p>
<!--Set you attribute as the value of the lightning:input component-->
<lightning:input aura:name="val"
label ="Enter KPI"
value="{!v.val}"
type="text"
onchange="{!c.onChange}"/>
</p>
</div>
</lightning:card>
My JS controller looks like
({
onChange : function(component, event, helper) {
var action = component.get("c.getCallKPI")
action.setParams({
"value":val,
})
$A.enqueueAction(action)
}
})
I tried to do the iteration portion in controller using following code
var prediction=component.find("pred")
var predictionProb=component.find("predProb")
<aura:iteration items="{c.getCallKPI}" var="predUrl" >
prediction.value="{!predUrl.label}"
predictionProb.value="{!prediction.probability}"
</aura:iteration>
where prediction & predictionProb are id of two lightning inputs given in my component.But I'm getting syntax error at </aura:iteration>
If I'm doing it in component using following code
<aura:iteration items="{c.getCallKPI}" var="predUrl" >
<lightning:input id="pred" readonly="true" value="{!predUrl.label}"/>
<lightning:input id="predProb" readonly="true" value="{!predUrl.probability}" />
</aura:iteration>
Then it's not giving any error but not populating the inputs.
Can you guide how do I resolve this?
my getCallKPI is given below
#auraEnabled
public static List<KPI.Prediction> getCallKPI(string value) {
return KPI.Prediction;
}
You should use aura:iteration inside component markup.
In your component create new attribute of type "List".
<aura:attribute name="predictions" type="List"/>
In JS controller specify callback for action, in which set new attribute to response.getReturnValue().
action.setCallback(this, function(response) {
component.set("v.predictions", response.getReturnValue());
}
Calling a Server-Side Action
Inside component, iterate over returned records:
<aura:iteration items="{!v.predictions}" var="item">
//your logic
</aura:iteration>
aura:iteration

Validation is not working properly in angularjs

I have created a login page with validations. I'm using Routes for the page navigations. At first I have redirection from index page to login page.(i.e., index->login) Then my validations worked perfectly fine.
Recently I have added a new home page. So, I'm loading this page first( i.e.,
index -> home -> login). This page contains a link to login page.
The problem now is my validation is not working properly. The error messages are shown on the page load itself.
Below is the code :
<div class='form-fields'>
<input type='email' name='mail_name' ng-model='mail' ng-pattern="emailFormat" required />
<span class="error" ng-show="login.mail_name.$error.pattern">Not valid email!</span>
</div>
<div class='form-fields'>
<input class='input-fields' type='password' name='pwd_name' ng-model='password' ng-pattern='passwordFormat' required />
<span class="error" ng-show="login.pwd_name.$error.pattern">Passowrd Error Message</span>
</div>
Js File :
$scope.mail = '';
$scope.emailFormat = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
$scope.password = '';
$scope.passwordFormat = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/;
Where I'm I going wrong?

Setting Value to ngtypeahead in Model Driven Form(Reactive)

I am using Angular Reactive form and having typeahead field via ng-bootstrap typeahead. I am having a list of states created using interface as below -
export interface IContactStates {
Id: number;
Name: string;
}
List of states is populated via service and typeahead is initialized in component.ts as -
search = (text$: Observable<string>) =>
text$
.debounceTime(200)
.distinctUntilChanged()
.map(term => term === '' ? []
: this.statesList.filter(v =>
v.Name.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
formatter = (x: {Name: string}) => x.Name;
and ngbTypahead is defined as below in html template -
<ng-template #rt let-r="result" let-t="term">
{{ r.Name}}
</ng-template>
<div class="col-md-6">
<div class="form-group input-group-sm"
[ngClass]="{'has-error': displayMessage.State}">
<label for="State">State</label>
<input class="form-control form-control-sm" formControlName="State"
type="text" [ngbTypeahead]="search"
[resultTemplate]="rt"
[resultFormatter]="formatter"
[inputFormatter]="formatter"
[editable]="false"
placeholder="State (start typing the name and then select from list)"
(selectItem)="selectItem($event)">
<span class="help-block" *ngIf="displayMessage.State">
{{displayMessage.State}}
</span>
</div>
</div>
This works fine when I am creating new form but when I am trying to edit any already submitted form, State control value is setting undefined. I tried to get any hint on setting the typeahead value from ng-bootstrap help documents but no luck.
Ok. I make it to work. Just reinitialize the form control element again.
Update 1
After getting value from server for selected item, search and assign the object to my formcontrol.
const state = this.statesList.find(function(item){
return item.Id === trader.State;
Then, patch the Typeahead control with this variable.

AngularJS ui-router re-render

I using ui-router to render a view. After render, how to re-render the view after perform some activity in the view (example return data after searching).
My problem is after render the View, I click a search button to search some records from database. But I don't know how to render the View again. Anything that I need to do in the View's search button?
Hope can give some example to me on how to solve it. Thank you.
var myApp = angular.module('myApp', ['ui.router']);
myApp .config(function($urlRouterProvider, $stateProvider){
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home/Main'
})
})
<div class="col-sm-9">
<div ui-view></div> //render menu content
</div>
Above is Menu Layout
<input id="txtsearch" class="form-control" placeholder="Search member ID or email" />
<input type="submit" id="btnsearch" value="Search" />
Above is View

Angular JS - Change path, Same controller, don't reload scope

I know it's been asked so many times here and I found it too. But it could not solve my problem.
Here is the case. I have one AngularJS application.
I have a list page. I have a button to add. When I click on add button, a pop-up window will come with a form. I want to change the URL when the pop-up comes but in the same controller.
Also I would like to add some other buttons on each, some html display as popup-or other location, but same controller without reloading all scope when url changes.
What I have tried.
app.js
var WebClientApp = angular.module('WebClientApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.bootstrap',
'ngRoute'
]);
WebClientApp.config(function ($routeProvider) {
$routeProvider
.when('/groups/:template', {
templateUrl: 'groups.html',
controller: 'GroupCtrl'
}
groups.html
<div>
<button ng-click="showAdd()">Add Group</button>
<div ng-include src="views/listpage.html">
<div ng-if="addGroupModal" class="popup-modal">
<form name="addGroup" ng-submit="addandEditGroup()">
<input type="text" ng-model="group.name">
</form>
<div>
<div ng-if="editGroupModal" class="popup-modal">
<form name="editGroup" ng-submit="saveGroup()">
<input type="text" ng-model="group.name">
<input type="text" ng-model="group.desc">
<input type="text" ng-model="group.id">
</form>
<div>
Controllers.js
WebClientApp.controller('GroupCtrl', function ($scope,$http, $location, $routeParams) {
$scope.group = {};
$scope.showAdd=function(){
$location.path('/groups/add');
}
var template = $routeParams.template;
switch(template){
case 'add':
loadAddPage();
break;
case 'edit':
loadEditPage();
break;
default:
loadListPageHideAll();
break;
}
function loadAddPage() {
$scope.addGroupModal=true;
$scope.editGroupModal=false;
}
function loadEditPage(){
$scope.addGroupModal=false;
$scope.editGroupModal=true;
}
function loadListPageHideAll() {
$scope.addGroupModal=false;
$scope.editGroupModal=false;
// connect to server and list all groups
}
$scope.addandEditGroup = function() {
$location.path('/groups/edit');
}
$scope.saveGroup = function() {
// Save group with $scope.group.
$location.path('/groups');
}
});
When I click on add button, it will show the add form. When I enter group name, and submit, it should show edit form after changing url with the group name filled in the form. But when I try, the value of group object becomes empty since the url is changing. I added the following in controller, but don't know what to do exactly after.
$scope.$on('$routeChangeStart', function(event, present, last) {
console.log(event,present,last);
});
How to assign the scope variables of last route to present route scope. I tried reload on search to false also, But it didnt work.
There might be an error here :
function loadEditPage(){
$scope.addGroupModal=false;
$scope.editGroupModal=true;
}
There are probably some typos in the HTML template code you posted, but what you are basically doing is hiding the parent addGroupModal and showing the child editGroupModal. Remove the nesting and the tags like this:
<div ng-if="addGroupModal" class="popup-modal">
<form name="addGroup" ng-submit="addandEditGroup()">
<input type="text" ng-model="group.name">
</form>
</div>
<div>
<div ng-if="editGroupModal" class="popup-modal">
<form name="editGroup" ng-submit="saveGroup()">
<input type="text" ng-model="group.name">
<input type="text" ng-model="group.desc">
<input type="text" ng-model="group.id">
</form>
</div>
</div>
Here is the plunkr ( hit enter to submit the form): http://plnkr.co/edit/MGT8HZ4lpgVWCkWlt8Ak?p=preview
If this is what you want to acheive, honestly you are complicating things ... There are simpler solutions.
I see! What you want to acheive is to have a reference of the old group variable before the route was changed... And you want to do that using the same controller...
Ok, to get the group from the last controller, you are half way there . You have to store the group somewhere because the targetScopes and currentScopes you receive in the $routeChange listeners don't point to the scopes.
http://plnkr.co/edit/HfK3fhVtZ4bxHtpiFR3B?p=preview
$scope.group = $rootScope.group || {};
$scope.$on('$routeChangeStart', function(event, present, last) {
console.log('start change route');
$rootScope.group = event.currentScope.group;
console.log('target scope group ',event.currentScope.group);
});
I agree the rootScope might not be the best place to keep that variable, but you can also put it inside an angular constant of variable.

Resources