AngularJS doesn't work in MVC Partial Views - asp.net-mvc

I'm currently working on a ASP.NET MVC project. The sites of the web application are created with Bootstrap. Later I added some AngularJS script to be able to translate the page into different languages. This works fine for all the pages, but not so if a partial view is loaded from a page.
So, for example I have a page to search for rollout objects by name or host name. On the page all the angular expressions in curly braces are evaluated properly and are replaced with strings in several languages by using a translate script. Now if I filter the objects by one of the three attributes the partial view for that page is loaded showing the results of the search, but here are the angular expressions not evaluated and it just shows the expressions themselves.
Here is the page where it works properly:
#{
ViewBag.Title = "{{ 'ROLLOUT-OBJECT_MANAGEMENT.TITLE' | translate }}";
}
<!-- html -->
<div style="font-size: 20px; margin-top: 20px; margin-bottom: 20px;">
<div class="gray-background list-group-item" translate="{{'ROLLOUT-OBJECT_MANAGEMENT.TITLE'}}"></div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<div class="row margin-bottom">
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.FIRST_NAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.SURNAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.HOST_NAME'}}"></h6>
</div>
</div>
<div class="row margin-bottom">
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iFirstName" name="iFirstName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iSurName" name="iSurName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iHostName" name="iHostName" placeholder="">
</div>
<div class="col-md-3">
<!-- getPartial() added to click through javascript-->
<button type="submit" class="btn btn-primary btn-block" id="iButton"><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.BUTTON_SEARCH'}}"></span><span class="white-color glyphicon glyphicon-search"></span></button>
</div>
</div>
</div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<h5><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.RESULTS'}}"></span><span class="purple-color glyphicon glyphicon-globe"></span></h5>
</div>
<!-- referenced in getPartial() -->
<div class="gray-background list-group-item">
<div class="row">
<div class="col-md-12" id="partialViewContainer">
#{Html.RenderPartial("_RolloutObjectManagementResultsPartial");}
</div>
</div>
</div>
</div>
<!-- layout -->
#Styles.Render(
"~/content/chosen/chosen.css",
"~/content/chosen/prism.css",
"~/content/chosen/style.css",
"~/content/bootstrap.css",
"~/content/Site.css")
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script>
//add functionality to button
$('#iButton').click(function () {
getPartial('0');
});
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
//alert(xhr.responseText);//debug
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
And here is the partial view where it doesn't work (important are the expressions in {{...}}:
<!-- Import needed namespaces -->
#using RolloutTool.BusinessLayer.Foundation
#using RolloutTool.Utility
<!-- Initializing needed variables -->
#{
List<RolloutObject> RolloutObjects = ViewContext.Controller.ViewBag.RolloutObjects;
List<Cluster> Clusters = ViewContext.Controller.ViewBag.Clusters;
string name = "";
int count = 0;
string rowID = "";
int page = 0;
if (ViewContext.Controller.ViewBag.Page != null)
{
page = ViewContext.Controller.ViewBag.Page;
}
}
<!-- html elements -->
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EMPLOYEE'}}"></h6></th>
<th style="width:20%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.WORK_STATION'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EDIT'}}"></h6></th>
<th class="text-center" style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.CLUSTER'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.ASSIGN'}}"></h6></th>
</tr>
</thead>
<tbody>
<!-- creating all RolloutObject Table rows -->
#foreach (RolloutObject ro in RolloutObjects)
{
<!-- generating rowID -->
rowID = "row" + Convert.ToString(count);
count++;
<!-- generating the full employee name -->
name = Functions.TryGetValue(ro.Employee.FirstName) + " " + Functions.TryGetValue(ro.Employee.SecondName) + " " + Functions.TryGetValue(ro.Employee.Name);
<tr id="#rowID">
<td>#name</td>
<td id="#Convert.ToString(rowID + "_hn")">#Convert.ToString(Functions.TryGetValue(ro.Hostname))</td>
<!-- generate link to right rolloutobjectedit -->
<td class="text-center"><span class="btn-pencil glyphicon glyphicon-pencil blue-color glyph-hov" onclick="location.href='#Url.Action("RolloutObjectEdit", "RolloutObject", new {hostName = ro.Hostname })'"></span></td>
<!-- generating the link for cluster addition and populating cluster dropdown -->
<td class="text-center">
<div class="row">
<div class="col-sm-12">
<select class="chosen-select no-margin" style="width:100%" id="#Convert.ToString(rowID + "_cl")" name="iCluster" data-placeholder="Cluster">
#if (ro.Cluster != null)
{
<option selected>#Convert.ToString(Functions.TryGetValue(ro.Cluster.Name))</option>
}
else
{
<option></option>
}
#foreach (Cluster cluster in Clusters)
{
<option>#Convert.ToString(Functions.TryGetValue(cluster.Name))</option>
}
</select>
</div>
</div>
</td>
<td class="text-center"><span class="btn-ok glyphicon glyphicon-ok green-color glyph-hov" onclick="callAjax('#rowID')" /></td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input class="hidden" id="hPage" value="#Convert.ToString(page)" />
<nav>
<ul class="pager">
<li class="pull-left"><a class="btn-paging glyphicon glyphicon-arrow-left" onclick="previous()"></a></li>
<li class="pull-right"><a class="btn-paging glyphicon glyphicon-arrow-right" onclick="next()"></a></li>
</ul>
</nav>
</div>
</div>
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script>
function callAjax(idRow) {
//get row values
var tempTD = document.getElementById(idRow + "_hn");
var tempSelect = document.getElementById(idRow + "_cl");
var tempHostName = tempTD.textContent;
var tempCluster = tempSelect.options[tempSelect.selectedIndex].text;
//ajax call
$.ajax({
url: "AddToCluster",
type: "POST",
data: { clusterName: tempCluster, hostName: tempHostName },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
This is the _Layout.cshtml where the scripts are contained and loaded:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - {{ 'TITLE.PROGRAM' | translate }}</title>
#Styles.Render(
"~/Content/css",
"~/Content/flag-icon-css-master/assets/docs.css",
"~/Content/flag-icon-css-master/css/flag-icon.min.css",
"~/Content/Site.css")
<script src="~/Scripts/angular/angular.js"></script>
<script src="~/Scripts/angular/angular-translate.js"></script>
<script src="~/Scripts/angular/angular-cookies.min.js"></script>
<script src="~/Scripts/angular/translate.js"></script>
<script src="~/Scripts/angular/angular-route.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-cookie.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-local.min.js"></script>
</head>
<body ng-controller="Ctrl">
<!-- Here is the html for the navigation bar etc. -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
I am really not an expert on AngularJS as I only wanted to provide some cool translation feature, but I hope you guys have an idea why it doesn't work in the partial views.

Its just that you need to call the partial view using ng-include("'controller/action'"). Apostrophe(') is important while writing url.
Example
<div id="TestDiv" ng-include="templateUrl"></div>
and inside the angular controller
var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope, $http, $sce) {
//Initially
$scope.templateUrl = '/Home/DefaultPage';
// To dynamically change the URL.
$scope.NewProjFn = function () {
$scope.templateUrl = '/Home/ProjectPage';
};
});
It might well not at all be difficult for you to re-implement it but by using ng-include you also need not to make an ajax call. It do it all by itself which includes ajax call, compilation and display. But the functions like ng-click and other events will not work as its a one time compilation process.

Related

jquery / Ajax "undefined" error

i am trying to get an image uploader working inside my MVC project, but everytime i click the upload file button, i get "Error undefined", i am not sure where i am going wrong.
The page is a partial view, loaded inside a #Html.BeginForm . below is the code i am using.
Index.cshtml
#using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="container">
<div class="row">
<article class="col-sm-12 col-md-12 col-lg-12 sortable-grid ui-sortable">
<div id="wid-id-0">
<!-- widget div-->
<div role="content">
<!-- widget content -->
<div class="widget-body">
<div class="row" style="background: white">
<form id="wizard-1" novalidate="novalidate">
<div id="bootstrap-wizard-1" class="col-sm-12">
<div class="tab-content">
#*Tab 1 (Step 1)*#
<div class="tab-pane active" id="tab1">
<br>
#Html.Partial("Registration/_Step1")
<div class="form-actions">
<div class="row">
<div class="col-sm-12">
<ul class="pager wizard no-margin">
<li class="previous disabled">
Previous
</li>
<li data-target="#step2" class="next">
Next
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="form-bootstrapWizard">
<ul class="bootstrapWizard form-wizard" style="background: coral">
<li class="active" data-target="#step1">
<span class="step">1</span> <span class="title">Step 1: Profile Information</span>
</li>
<li data-target="#step2" class="">
<span class="step">2</span> <span class="title">Step 2: Profile Picture</span>
</li>
<li data-target="#step3" class="">
<span class="step">3</span> <span class="title">Step 3: Identification</span>
</li>
<li data-target="#step4">
<span class="step">4</span> <span class="title">Step 4: Submit Profile</span>
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>
</form>
</div>
</div>
<!-- end widget content -->
</div>
<!-- end widget div -->
</div>
<!-- end widget -->
</article>
</div>
</div>
}
_Step1.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("UploadFiles", "Account")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("error: " + error.statusMessage);
}
});
});
});
</script>
<table align="center">
<tr>
<td style="text-align: center;"><label>Upload Profile Picture</label></td>
<td></td>
</tr>
<tr>
<td valign="top"><img id="imgPreview" src="~/Content/Images/upload_holder.PNG" class="img-holder" style="width: 180px; height: 180px;" /></td>
<td>
#*<input type="submit" class="btn btn-lg" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo" />*#
#*<input id="input-4" name="input4[]" type="file" multiple class="file-loading" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo">*#
<input type="file" id="FileUpload" multiple />
<input type="submit" id="Upload" value="Upload"/>
<br />
<br />
<label>Acceptable file formats: jpg, gif or png file</label>
<br />
<label>Under 1 MB</label>
</td>
</tr>
</table>
any help is greatly appreciated!
EdIT: Below is the controller function, but its never hit.
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Foreach not updating HTML list elements

Using knockout 2.2.0
I'm trying to use the same dialog for add and edit. I have the code mostly working, but when I replace the observable with the new edited one, it doesn't cause an update in the foreach (or at least it continues to display the old values) It does update the actual model, as I can see in dev tools. I even tried to force an update with .valueHasMutated(), but with no luck.
self.editReference = function () {
self.isEdit(true);
self.open();
self.dialogReferences(this);
};
self.saveEditReference = function () {
self.references.replace(this, self.dialogReferences);
self.references.valueHasMutated();
self.dialogReferences(newReferences());
self.close();
};
And here is the some of the partial view with the references section of HTML code:
<ul class="sortable references-summary" data-bind="foreach: references">
<li class="ui-state-default"><b>Name: </b><!-- ko text:name --><!-- /ko--><br /><b>Company: </b><!-- ko text:company --><!-- /ko--><span class="ui-icon ui-icon-closethick"></span><span class="ui-icon ui-icon-wrench"></span></li>
</ul>
Thanks to CrimsonChris for pointing out my bug. The updated code below works as expected.
The approach is to have a reference you are editing, in addition to the references in your array. When you start to edit, you copy the values from the array to your edit reference. When you save the edit, you copy them back. There is no need for valueHasMutated for this to work.
function reference(name, company) {
return {
name: ko.observable(name),
company: ko.observable(company)
};
}
// Copy r1 into r2
reference.copy = function(r1, r2) {
r2.name(r1.name());
r2.company(r1.company());
}
var self = {
editingReference: undefined,
dialogReferences: reference('', ''),
references: ko.observableArray([
reference('One', 'First Company'),
reference('Two', '2nd Company')
]),
dialogIsOpen: ko.observable(false),
open: function() {
self.dialogIsOpen(true);
},
close: function() {
self.dialogIsOpen(false);
}
};
self.editReference = function(item) {
self.editingReference = item;
self.open();
reference.copy(item, self.dialogReferences);
};
self.removeReference = function(item) {
self.references.remove(item);
self.close();
};
self.saveEditReference = function(item) {
reference.copy(item, self.editingReference);
self.close();
};
ko.applyBindings(self);
<link href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<ul class="sortable references-summary" data-bind="foreach: references">
<li class="ui-state-default"> <b>Name: </b>
<!-- ko text:name() -->
<!-- /ko-->
<br /> <b>Company: </b>
<!-- ko text:company() -->
<!-- /ko--> <span class="ui-icon ui-icon-closethick"></span>
<span class="ui-icon ui-icon-wrench"></span>
</li>
</ul>
<div data-bind="if: dialogIsOpen">
<div data-bind="with:dialogReferences">
<label>Name</label>
<input data-bind="value:name" />
<br/>
<label>Company</label>
<input data-bind="value:company" />
<input type="button" value="Save" data-bind="click: $parent.saveEditReference" />
</div>
</div>

Slow behavior pushPage Onsen UI

I'm having problems with pushPage slide animation (slow behavior) between pages.
Cordova 4.3.0 / OnsenUI 1.3.0 / iOs 8.3.
Maybe fastClick isn't working!?
Anyone can help me to find this bug?
Code:
Index.html
<ons-sliding-menu
menu-page="pages/menu.html" main-page="pages/page1.html" side="left"
var="menu" type="reveal" max-slide-distance="65%" swipable="true">
</ons-sliding-menu>
page1.html
<ons-navigator var="appNavigator">
<ons-modal var="modal1" style="display:none;" id="modal1">
<ons-icon size="20px" spin="true" icon="ion-load-c"></ons-icon>
<br><br>
Loading...
</ons-modal>
<ons-page ng-controller="controller1">
<ons-pull-hook ng-action="load($done)" var="loader">
<span ng-switch="loader.getCurrentState()">
<span ng-switch-when="initial" style="opacity:0.7;font-size:12px;color:#e23b3c;"><ons-icon style="color:#e23b3c;" size="20px" icon="ion-arrow-down-a"></ons-icon> Baja para actualizar</span>
<span ng-switch-when="preaction" style="opacity:0.7;font-size:12px;color:#e23b3c;"><ons-icon style="color:#e23b3c;" size="20px" icon="ion-arrow-up-a"></ons-icon> Suelta para actualizar</span>
<span ng-switch-when="action" style="opacity:0.7;font-size:12px;color:#e23b3c;"><ons-icon style="color:#e23b3c;" size="20px" spin="true" icon="ion-load-c"></ons-icon> Loading...</span>
</span>
</ons-pull-hook>
<ons-toolbar style="background-color:#e23b3c;">
<div class="left">
<ons-toolbar-button ng-click="menu.toggle()">
<ons-icon icon="ion-navicon" size="28px" fixed-width="false" style="color:#fff;"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center" style="color:#fff;">TITLE...</div>
</ons-toolbar>
<section style="height:100%;">
<ons-list id="lista_descuentos" style="width:100%;height:100%;">
<ul>
<li ng-click="showDetail($index)" ng-repeat="data in todo.all" class="list__item list__item--tappable list__item__line-height list-item-container list__item--chevron">
<div class="ribbon-wrapper-green">
<div class="ribbon-green">{{data.data1}}%</div>
</div>
<div class="list-item-main">
<div class="list-item-left" ng-if="data.data2 == 1">
<img src="urlXXX/{{data.data3}}" class="thumbnail"/>
</div>
<div class="list-item-left" ng-if="data.data2 != 1">
<img src="urlXXX/{{data.data3}}" class="thumbnail desaturate"/>
</div>
<div class="list-item-right">
<div class="list-item-content">
<span class="list-item-name">{{data.data4}}<br/>
<span class="lucent">{{data.data5}}</span>
</span>
<br/>
</div>
</div>
</div>
<span class="list-item-action"></span>
</li>
</ul>
</ons-list>
</section>
</ons-page>
page2.html
<ons-page ng-controller="controller2">
<ons-toolbar style="background-color:#e23b3c;">
<div class="left" style="color:#fff;"><ons-back-button >Back</ons-back-button></div>
<div class="center" style="color:#fff;">{{data1}}</div>
</ons-toolbar>
<div style="height:100%;width:100%;background-position:center; background-repeat:no-repeat; background-size:cover;background-color: #333;background-size:cover;" class="desaturateDiv">
<div class="dots"></div>
<div style="position:absolute;bottom:0;width:100%;height:100%;background-color:rgba(51, 51, 51, 0.6);z-index:90;">
</div>
<div style="position:absolute;bottom:0;width:100%;height:30%;background-color:rgba(51, 51, 51, 0.7);z-index:91;color:#fff;">
{{dato2}}
</div>
</div>
app.js
module.controller('controller1', function($scope, $http, info) {
var firstTime = 1;
var getData = function ($done) {
if (firstTime==1){
modal1.show();
}
$http({method: 'GET', url: info.url}).
success(function(data, status, headers, config) {
if ($done) { $done(); }
$scope.todo = data;
if (firstTime==1){
modal1.hide();
}
}).
error(function(data, status, headers, config) {
if ($done) { $done(); }
alert('error');
modal1.hide();
});
}
// Initial Data Loading
getData();
$scope.load = function($done) {
firstTime = 0;
getData($done);
};
$scope.showDetail = function(index) {
var selectedItem = $scope.todo.all[index];
console.log('asd: '+selectedItem.data1);
$scope.appNavigator.pushPage('pages/page2.html',{data1:selectedItem.data1, data2:selectedItem.data2, data3:selectedItem.data3});
}
});
module.controller('controller2', function($scope) {
$scope.data1 = appNavigator.getCurrentPage().options.data1;
$scope.data2 = appNavigator.getCurrentPage().options.data2;
$scope.data3 = appNavigator.getCurrentPage().options.data3;
});
I get no 300ms delay if the meta viewport tag is configured correctly.
With the following viewport settings pinch zoom is disabled so there should be no delay:
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
Onsen UI will dynamically set the viewport tag if there is none defined.

Angularjs ReferenceError: post is not defined

I'm working on a simple app that create posts and comments to learn how to create ROR apps implemented with Angularjs.
I'm finding a problem as I'm trying to make my addComment function work. Seems like the variable that holds the expected object is not defined. At least this is the message I got from network inspection
ReferenceError: post is not defined
at k.$scope.addComment (http://localhost:3000/javascripts/app.js:99:34)
at bb.functionCall (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:176:141)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:193:165
at k.$get.k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:112:319)
at k.$get.k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:113:48)
at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:193:147)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:31:225
at Array.forEach (native)
at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:7:280)
at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:31:207)angular.js:9959 (anonymous function)angular.js:7298 $getangular.js:12695 $get.k.$applyangular.js:18941 (anonymous function)angular.js:2822 (anonymous function)angular.js:325 qangular.js:2821
If someone can se a problem in my code that points to this error please let me know.
follows my code
angular.module('flapperNews', ['ui.router'])
//Provider
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
$urlRouterProvider.otherwise('home');
}])
//Posts service
.factory('posts', ['$http', function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
o.create = function(post) {
return $http.post('/posts.json', post).success(function(data){
o.posts.push(data);
});
};
o.addComment = function(id, comment) {
return $http.post('/posts/' + id + '/comments.json', comment);
};
return o;
}])
//Main Controller
.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title == '') { return; }
posts.create({
title: $scope.title,
link: $scope.link
});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
}])
//Posts Controller
.controller('PostsCtrl', [
//the $scope declares that it will have elements visible in the view
'$scope',
'$stateParams',
//the posts under is the service
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
posts.addComment( post.id, {
body: $scope.body,
author: 'user'
}).success(function(comment){
$scope.post.comments.push(comment);
});
$scope.body = '';
};}]);
and the html
<!DOCTYPE html>
<html>
<head>
<title>FlapperNews</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="javascripts/app.js"></script>
<script src="javascripts/application.js"></script>
<%= csrf_meta_tags %>
</head>
<body ng-app="flapperNews">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(post)"></span>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
<span>
Comments
</span>
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title">
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link">
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
<script type="text/ng-template" id="/posts.html">
<div class="page-header">
<h3>
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</h3>
</div>
<div ng-repeat="comment in post.comments | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(comment)"></span>
{{comment.upvotes}} - by {{comment.author}}
<span style="font-size:20px; margin-left:10px;">
{{comment.body}}
</span>
</div>
<form ng-submit="addComment()"
style="margin-top:30px;">
<h3>Add a new comment</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Comment"
ng-model="body">
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
</body>
</html>
I think the problem is here Comments. You missed {. Because of which it is unable to find the stateparam id, which you are using to create post object on controller's scope.

jQuery Mobile collapsible panel and KNockjs observable array

Can someone help me to figure out why my collapsible panel won't expand? My html markup with jquery mobile appears to be working. The data gets bound to the collapsible set via a foreach loop, but the panels will not expand.
html:
<div data-role="collapsible-set" class="ui-block-a" data-bind="foreach: opportunityData">
<div data-collapsed="true" data-role="collapsible" >
<h3>
<span data-bind="text: name" />
</h3>
<p data-bind="text: company" />
</div>
</div>
JS:
function OpportunityViewModel() {
var self = this;
self.opportunityData = ko.observable([]);
$.ajax({
url: 'url....',
type: 'GET',
async: true,
cache: false,
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
self.opportunityData(data)
},
error: function (jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
}); //end ajax call
}; //end viewmodel
ko.applyBindings(new OpportunityViewModel());
});
I just found the solution, just create a new out side div then put foreach in that div:
<div data-bind="foreach: opportunityData">
<div data-role="collapsible-set" class="ui-block-a" >
<div data-collapsed="true" data-role="collapsible" >
<h3>
<span data-bind="text: name" />
</h3>
<p data-bind="text: company" />
</div>
</div>
</div>

Resources