I've just started developing with Angular schema form and I'm struggling to write any tests for my custom field directive.
I've tried compiling the schema form html tag which runs through my directives config testing it's display conditions against the data in the schema. However it never seems to run my controller and I can't get a reference to the directives HTML elements. Can someone give me some guidance on how to get a reference to the directive? Below is what I have so far:
angular.module('schemaForm').config(['schemaFormProvider',
'schemaFormDecoratorsProvider', 'sfPathProvider',
function(schemaFormProvider, schemaFormDecoratorsProvider, sfPathProvider) {
var date = function (name, schema, options) {
if (schema.type === 'string' && schema.format == 'date') {
var f = schemaFormProvider.stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'date';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
schemaFormProvider.defaults.string.unshift(date);
schemaFormDecoratorsProvider.addMapping('bootstrapDecorator', 'date',
'app/modules/json_schema_form/schema_form_date_picker/schema_form_date_picker.html');
}]);
var dateControllerFunction = function($scope) {
$scope.isCalendarOpen = false;
$scope.showCalendar = function () {
$scope.isCalendarOpen = true;
};
$scope.calendarSave = function (date) {
var leaf_model = $scope.ngModel[$scope.ngModel.length - 1];
var formattedDate = $scope.filter('date')(date, 'yyyy-MM-dd');
leaf_model.$setViewValue(formattedDate);
$scope.isCalendarOpen = false;
};
};
angular.module('schemaForm').directive('schemaFormDatePickerDirective', ['$filter', function($filter) {
return {
require: ['ngModel'],
restrict: 'A',
scope: false,
controller : ['$scope', dateControllerFunction],
link: function(scope, iElement, iAttrs, ngModelCtrl) {
scope.ngModel = ngModelCtrl;
scope.filter = $filter
}
};
}]);
<div ng-class="{'has-error': hasError()}">
<div ng-model="$$value$$" schema-form-date-picker-directive>
<md-input-container>
<!-- showTitle function is implemented by ASF -->
<label ng-show="showTitle()">{{form.title}}</label>
<input name="dateTimePicker" ng-model="$$value$$" ng-focus="showCalendar()" ng-disabled="isCalendarOpen">
</md-input-container>
<time-date-picker ng-model="catalogue.effectiveFrom" ng-if="isCalendarOpen" on-save="calendarSave($value)" display-mode="date"></time-date-picker>
</div>
<!-- hasError() defined by ASF -->
<span class="help-block" sf-message="form.description"></span>
</div>
And the spec:
'use strict'
describe('SchemaFormDatePicker', function() {
var $compile = undefined;
var $rootScope = undefined;
var $scope = undefined
var scope = undefined
var $httpBackend = undefined;
var elem = undefined;
var html = '<form sf-schema="schema" sf-form="form" sf-model="schemaModel"></form>';
var $templateCache = undefined;
var directive = undefined;
beforeEach(function(){
module('app');
});
beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_, _$httpBackend_) {
$compile = _$compile_
$rootScope = _$rootScope_
$httpBackend = _$httpBackend_
$templateCache = _$templateCache_
}));
beforeEach(function(){
//Absorb call for locale
$httpBackend.expectGET('assets/locale/en_gb.json').respond(200, {});
$templateCache.put('app/modules/json_schema_form/schema_form_date_picker/schema_form_date_picker.html', '');
$scope = $rootScope.$new()
$scope.schema = {
type: 'object',
properties: {
party: {
title: 'party',
type: 'string',
format: 'date'
}}};
$scope.form = [{key: 'party'}];
$scope.schemaModel = {};
});
describe("showCalendar", function () {
beforeEach(function(){
elem = $compile(html)($scope);
$scope.$digest();
$httpBackend.flush();
scope = elem.isolateScope();
});
it('should set isCalendarOpen to true', function(){
var result = elem.find('time-date-picker');
console.log("RESULT: "+result);
));
});
});
});
If you look at the below example taken from the project itself you can see that when it uses $compile it uses angular.element() first when setting tmpl.
Also, the supplied test module name is 'app' while the code sample has the module name 'schemaForm'. The examples in the 1.0.0 version of Angular Schema Form repo all use sinon and chai, I'm not sure what changes you would need to make if you do not use those.
Note: runSync(scope, tmpl); is a new addition for 1.0.0 given it is now run through async functions to process $ref includes.
/* eslint-disable quotes, no-var */
/* disabling quotes makes it easier to copy tests into the example app */
chai.should();
var runSync = function(scope, tmpl) {
var directiveScope = tmpl.isolateScope();
sinon.stub(directiveScope, 'resolveReferences', function(schema, form) {
directiveScope.render(schema, form);
});
scope.$apply();
};
describe('sf-array.directive.js', function() {
var exampleSchema;
var tmpl;
beforeEach(module('schemaForm'));
beforeEach(
module(function($sceProvider) {
$sceProvider.enabled(false);
exampleSchema = {
"type": "object",
"properties": {
"names": {
"type": "array",
"description": "foobar",
"items": {
"type": "object",
"properties": {
"name": {
"title": "Name",
"type": "string",
"default": 6,
},
},
},
},
},
};
})
);
it('should not throw needless errors on validate [ノಠ益ಠ]ノ彡┻━┻', function(done) {
tmpl = angular.element(
'<form name="testform" sf-schema="schema" sf-form="form" sf-model="model" json="{{model | json}}"></form>'
);
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
scope.model = {};
scope.schema = exampleSchema;
scope.form = [ "*" ];
$compile(tmpl)(scope);
runSync(scope, tmpl);
tmpl.find('div.help-block').text().should.equal('foobar');
var add = tmpl.find('button').eq(1);
add.click();
$rootScope.$apply();
setTimeout(function() {
var errors = tmpl.find('.help-block');
errors.text().should.equal('foobar');
done();
}, 0);
});
});
});
Related
I have a drop down list in the form of the select tag as shown below:
<select id = "1">
<option>Amy</option>
<option>Gi-Anne</option>
</select>
I want to pass the selected option - either Amy or Gi Anne to this method of the controller.
public String name (string nameSelected)
{
var query = new NameQuery();
if(nameSelected.Equals('Amy'))
{run a specific query}
else if(nameSelected.Equals('Gi-Anne'))
{run a specific query}
}
How do I pass the parameter of the selected drop down list value to the controller? Appreciate your help and thanks in advance.
This is 'fairly' easy using AngularJS, see this Plunk for a (simulated) example.
The HTML changes to this:
<body ng-app="myApp">
<div ng-controller="myController">
State: {{onChangeText}}
<br/>
<select ng-model="selectedItemId" id="itemList" ng-change="onChange()">
<option value="{{item.id}}" ng-selected="{{item.id == selectedItemId}}" ng-repeat="item in items">{{item.name}}</option>
</select>
<br/>
{{selectedQuery}}
</div>
</body>
With a controller like this:
app.controller("myController", [
"$scope",
"$http",
function($scope, $http){
var self = {};
self.simulatedGetQuery = function() {
console.log($scope.selectedItemId);
$scope.selectedQuery = "";
switch($scope.selectedItemId) {
case "1":
$scope.selectedQuery = "Query Amy";
break;
case "2":
$scope.selectedQuery = "Query Gi-Anne";
break;
}
};
self.httpGetQuery = function() {
$http({
method: 'GET',
url: 'http://somehostname/action/' + $scope.selectedItemId
}).then(function successCallback(response) {
$scope.selectedQuery = response;
}, function errorCallback(response) {
});
};
// -- SCOPED -- //
$scope.selectedItemId = 0;
$scope.items = [
{
"id": 1,
"name": "Amy"
},
{
"id": 2,
"name": "Gi-Anne"
}
];
$scope.onChange = function() {
$scope.onChangeText = "simulated GET triggered.";
self.simulatedGetQuery();
// Use this for actual GET
// self.httpGetQuery
};
// --- //
$scope.onChangeText = "waiting for user input";
$scope.selectedQuery = "no query selected. Chose a person for a valid query.";
}]);
It would need to be fleshed out in a real environment, but I think it will do for a simulated test. Check the scripts in the Plunk for a more detailed perspective on how to do this. All of this is clientside.
The URL of the $http call would be to your backend (MVC or Web API) controller.
I have a JsonResult method in my controller. I have pulled in data from my database and set to an object. The method will return this object. I am trying pass this data into AngularJS data source. I would like to display a DevExtreme bar chart. Here is code so far.
AngularJS file:
var app = angular.module('customApp', ['dx']);
app.controller("chartControl", function ($scope, $http) {
$scope.sizeSettings = {
dataSource: 'http://localhost:53640/Home/PostChart',
commonSeriesSettings: {
argumentField: 'product_id',
valueField: "product_id", name: "Product Cost",
type: "bar"
},
seriesTemplate: {
nameField: 'Source',
}
};
});
Home Controller:
public JsonResult PostChart(int product_id)
{
Object prod = null;
using (ProductOrderEntities db = new ProductOrderEntities())
{
var product = db.Products.FirstOrDefault(p => p.product_id == product_id);
prod = new {productID = product.product_id, productName = product.product_name, productPrice = product.product_cost, productDescription = product.product_type};
}
return Json(prod, JsonRequestBehavior.AllowGet);
}
}
HTML
<div ng-app="customApp">
<div ng-controller="chartControl">
</div>
</div>
Seems like you forget add markup for chart:
<div dx-chart="chartOptions"></div>
I've made a simple ASP.NET MVC application here https://www.dropbox.com/s/hk3viceoa2zkyng/DevExtremeChart.zip?dl=0
Open the start page http://localhost:56158/Default1/ to see chart in action.
See more information about using DevExtreme Charts in AngularJS app here http://js.devexpress.com/Documentation/Howto/Data_Visualization/Basics/Create_a_Widget/?version=14_2#Data_Visualization_Basics_Create_a_Widget_Add_a_Widget_AngularJS_Approach
This is how I solved it.
HTML
<div ng-app="customCharts">
<div ng-controller="ChartController">
<div dx-chart="productSettings"></div>
</div>
</div>
AngularJS
var app = angular.module('customCharts', ['dx']);
app.controller("ChartController", function ($scope, $http, $q) {
$scope.productSettings = {
dataSource: new DevExpress.data.DataSource({
load: function () {
var def = $.Deferred();
$http({
method: 'GET',
url: 'http://localhost:53640/Home/PostChart'
}).success(function (data) {
def.resolve(data);
});
return def.promise();
}
}),
series: {
title: 'Displays Product Costs for items in our Database',
argumentType: String,
argumentField: "Name",
valueField: "Cost",
type: "bar",
color: '#008B8B'
},
commonAxisSettings: {
visible: true,
color: 'black',
width: 2
},
argumentAxis: {
title: 'Items in Product Store Database'
},
valueAxis: {
title: 'Dollor Amount'
}
}
})
Controller
public JsonResult PostChart()
{
var prod = new List<Object>();
using (ProductOrderEntities db = new ProductOrderEntities())
{
var product = db.Products.ToList();
foreach (var p in product)
{
var thing = new { Name = p.product_name, Cost = p.product_cost };
prod.Add(thing);
}
}
return Json(prod, JsonRequestBehavior.AllowGet);
}
I have a JSON file which basically looks like this:
[
{
"First" : [...]
},
{
"Second" : [...]
},
{
"Third" : [...]
},
]
In my router i have:
this.totalCollection = new TotalCollection();
this.totalView = new TotalView({el:'#subContent', collection:this.totalCollection});
this.totalCollection.fetch({success: function(collection) {
self.totalView.collection=collection;
self.totalView.render();
}});
Now i have my Backbone Model:
define([
"jquery",
"backbone"
],
function($, Backbone) {
var TotalModel = Backbone.Model.extend({
url: "/TotalCollection.json",
initialize: function( opts ){
this.first = new First();
this.second = new Second();
this.third = new Third();
this.on( "change", this.fetchCollections, this );
},
fetchCollections: function(){
this.first.reset( this.get( "First" ) );
this.second.reset( this.get( "Second" ) );
this.third.reset( this.get( "Third" ) );
}
});
return TotalModel;
});
and my in my Backbone View i try to render the collection(s):
render: function() {
$(this.el).html(this.template(this.collection.toJSON()));
return this;
}
But I get the Error "First is not defined" - whats the issue here?
Have you actually defined a variable 'First', 'Second' and 'Third'? Based on what you're showing here, there is nothing with that name. One would expect you to have a couple lines like..
var First = Backbone.Collection.extend({});
var Second = Backbone.Collection.extend({});
var Third = Backbone.Collection.extend({});
However you haven't provided anything like that, so my first assumption is that you just haven't defined it.
Per comments, this may be more what you need:
render: function() {
$(this.el).html(this.template({collection: this.collection.toJSON())});
return this;
}
Then..
{{#each collection}}
{{#each First}}
/*---*/
{{/each}}
{{/each}}
I'm using mustache partials for our internal documentation and for testing - as described in this other SO question how to have grunt task render mustache partials to static HTML, and I'd now like to make the partials data driven using external json files. The json files would be named the same as the partials and will contain mock data that would compile with the partials.
Any suggestions on how to get this working?
I've updated the hogan.js file to read in data.json files that have the same name as the partials:
module.exports = function(grunt) {
// Grunt utilities.
var task = grunt.task,
file = grunt.file,
utils = grunt.util,
log = grunt.log,
verbose = grunt.verbose,
fail = grunt.fail,
option = grunt.option,
config = grunt.config,
template = grunt.template,
_ = utils._
// external dependencies
var fs = require('fs'),
hogan = require('hogan');
// ==========================================================================
// TASKS
// ==========================================================================
grunt.registerMultiTask('hogan', 'Compile mustache files to HTML with hogan.js', function() {
var data = this.data,
src = grunt.file.expandFiles(this.file.src),
dest = grunt.template.process(data.dest),
// Options are set in gruntfile
defaults = {
production: false,
docs: false,
title: 'Sellside',
setAccount: 'NA',
setSiteId: 'NA',
layout: 'docs/templates/layout.mustache',
paths: {},
partials: {},
partialsData: {},
},
options = _.extend(defaults, this.data.options || {})
!src && grunt.warn('Missing src property.')
if(!src) return false
!dest && grunt.warn('Missing dest property')
if(!dest) return false
var done = this.async()
var srcFiles = file.expandFiles(src)
if(options.paths.partials) {
var partials = grunt.file.expandFiles(options.paths.partials);
log.writeln('Compiling Partials...');
partials.forEach(function(filepath) {
var filename = _.first(filepath.match(/[^\\\/:*?"<>|\r\n]+$/i)).replace(/\.mustache$/, '');
log.writeln(filename.magenta);
var dataFilepath = filepath.replace(/\.mustache$/, '.json');
var partial = fs.readFileSync(filepath, 'utf8');
options.partials[filename] = hogan.compile(partial);
// if a data file exists, read in the data
if(fs.existsSync(dataFilepath)) {
options.partialsData[filename] = grunt.file.readJSON(dataFilepath);
}
});
log.writeln();
}
try {
options.layout = fs.readFileSync(options.layout, 'utf8')
options.layout = hogan.compile(options.layout, {
sectionTags: [{
o: '_i',
c: 'i'
}]
})
} catch(err) {
grunt.warn(err) && done(false)
return
}
srcFiles.forEach(function(filepath) {
var filename = _.first(filepath.match(/[^\\\/:*?"<>|\r\n]+$/i)).replace(/\.mustache$/, '')
grunt.helper('hogan', filepath, filename, options, function(err, result) {
err && grunt.warn(err) && done(false)
if(err) return
file.write(dest.replace('FILE', filename), result)
})
})
done()
})
// ==========================================================================
// HELPERS
// ==========================================================================
grunt.registerHelper('hogan', function(src, filename, options, callback) {
log.writeln('Compiling ' + filename.magenta);
var page = fs.readFileSync(src, 'utf8'),
html = null,
layout = options.layout,
context = {};
context[filename] = 'active';
context._i = true;
context.production = options.production;
context.docs = options.docs;
context.setAccount = options.setAccount;
context.setSiteId = options.setSiteId;
var title = _.template("<%= page == 'Index' ? site : page + ' · ' + site %>")
context.title = title({
page: _(filename).humanize().replace('css', 'CSS'),
site: options.title
})
try {
page = hogan.compile(page, {
sectionTags: [{
o: '_i',
c: 'i'
}]
})
context = _.extend(context, options.partialsData);
options.partials.body = page;
page = layout.render(context, options.partials)
callback(null, page)
} catch(err) {
callback(err)
return
}
})
};
A simple example of an alert.json file:
{
"modifier": "alert-warning",
"alertType": "Warning!",
"message": "Best check yo self, you're not looking too good."
}
alert.mustache
alerts
<div class="row-fluid">
<div class="alert {{alert.modifier}}">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{alert.alertType}}</strong>
{{alert.message}}
</div>
</div>
</div><!-- /container -->
I like this next example better because you can create different data to use
in the same partials:
alert.json
{
"default": {
"modifier": "alert-warning",
"alertType": "Warning!",
"message": "Best check yo self, you're not looking too good.!"
},
"error": {
"modifier": "alert-error",
"alertType": "Error!!!",
"message": "You did something horribily wrong!!!"
},
"success": {
"modifier": "alert-success",
"alertyType": "Success!!!",
"message": "The record has been successfully saved..."
}
}
alert.mustache
<!-- partial -->
<div class="container">
<h1>alerts</h1>
<div class="row-fluid">
<div class="alert {{modifier}}">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{alertType}}</strong>
{{message}}
</div>
</div>
</div><!-- /container -->
partials.mustache --- this is where the alert partial is referenced
{{#alert.default}}
{{> alert }}
{{/alert.default}}
{{#alert.error}}
{{> alert }}
{{/alert.error}}
{{#alert.success}}
{{> alert }}
{{/alert.success}}
Let me know if this helps.
Thanks,
Brian
Issue is related to this and this.
The problem is that when a options list is not yet populated with valid data (because the JSON call return is asynchronously), you cannot set the initial selected value.
function PersonViewModel() {
// Data members
this.Function_Id = ko.observable('#(Model.Function_Id)');
this.Functions = ko.observableArray([{ Id: '#(Model.Function_Id)', Name: ''}]); // This works
//this.Functions = ko.observableArray(); // This does not work
this.SubFunctions = ko.observableArray();
this.GetFunctions = function () {
var vm = this;
$.getJSON(
'#Url.Action("GetFunctions", "Function")',
function (data) {
vm.Functions(data);
if (vm.Function_Id() === undefined) {
//vm.Function_Id('#(Model.Function_Id)'); // Only way to solve my problem?
}
}
);
};
}
$(document).ready(function () {
var personViewModel = new PersonViewModel();
ko.applyBindings(personViewModel);
personViewModel.GetFunctions();
});
See this modified fiddle
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
var viewModel = {
selectedItem: ko.observable(),
//items: ko.observableArray([new Item(3, "")])
items: ko.observableArray()
};
ko.applyBindings(viewModel);
var selectedIndex = 3;
setTimeout(function() {
viewModel.items([
new Item(1, "pencil"),
new Item(2, "pen"),
new Item(3, "marker"),
new Item(4, "crayon")
]);
var selectedValue;
$.each(viewModel.items(), function(index, item) {
if (index === selectedIndex) {
selectedValue = item;
}
});
viewModel.selectedItem(selectedValue);
}, 1000);
h2 { font-size: 1.1em; font-weight: bold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select data-bind="options: items, optionsText: 'name', value: selectedItem"><option selected="selected"></option></select>
<div data-bind="with: selectedItem">
<span data-bind="text: name"></span>
</div>
Thanks to 'RP Niemeyer' and 'Sandeep G B', I've created this solution.
Maybe it's also an idea to add an 'initialValue' property to the data-bind functionality for a the data-bind attribute from a select like this:
<select id="Function_Id"
data-bind='
options: Functions,
optionsValue : "Id",
optionsText: "Name",
initialValue = 1,
value: Function_Id,
optionsCaption: Functions().length == 0 ? "Loading..." : "--NONE--"'>
</select>