Selector [ng\:model="query"] did not match any elements - asp.net-mvc

Why am I getting this error: Selector [ng\:model="query"] did not match any elements
I've read through this: AngularJS: End to End Testing Issue , but that link doesn't really apply in a .net env:
IDE: Visual Studio 2012
Project type: ASP.NET MVC4
File strucure:
Running CI tests through karma start e2e.conf.js in node.js command prompt
My karma conf:
basePath = '../../../';
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'angular/app/*.js',
'angular/Tests/e2e/*.js'
];
reporters = ['progress'];
port = 10876;
runnerPort = 10100;
colors = true;
logLevel = LOG_ERROR;
autoWatch = true;
browsers = ['Firefox'];
captureTimeout = 60000;
singleRun = false;
proxies = {
'/': 'http://localhost:60607/'
};
My e2e test:
describe('E2E: AMS', function () {
describe('Settings Users', function () {
beforeEach(function () {
browser().navigateTo('/#/settings/users');
});
it('filters the users list as the user types into the search box', function () {
expect(repeater('.users li').count()).toBe(2);
input('query').enter('abc');
expect(repeater('.users li').count()).toBe(1);
input('query').enter('efg');
expect(repeater('.users li').count()).toBe(1);
input('query').enter('ijk');
expect(repeater('.users li').count()).toBe(0);
});
});
});
My View:
<div data-ng-view="">
Add User: <br />
<input type="text" /> <button>Submit</button><br />
Search:
<input data-ng-model="query" type="text" />
Users <br />
<ul class="users">
<li data-ng-repeat="user in users | filter:query">
{{user.name}}
</li>
</ul>
</div>
and for grins, my route
angular.module('AMS', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/login', { templateUrl: '/AccessControl/Login/', controller: settingsController }).
when('/dashboard', { templateUrl: '/Dashboard/Dashboard', controller: dashboardController }).
when('/settings', { templateUrl: '/Settings/Settings', controller: settingsController }).
when('/settings/users', { templateUrl: '/Settings/Users', controller: settingsController }).
otherwise({ redirectTo: '/dashboard' });
}]);

It looks like the angular e2e testing api is looking for "ng-model" in your view instead of the "data-ng-model" that you're using.
My understanding is that both are valid, but give that a try to see if that's the problem.

Not an answer, so I wont mark it as such, this is more of a work around.
I've decided to go with chutzpah in order to run the jasmine unit tests, and specflow.xunit for "e2e" testing. It works well in a .net environment and integration into teamcity seems straight forward.

Related

Rails + Angular : Issue with directive

I have Rails 4.2.4 and Angular 1.4.8.
I am trying define a directive:
index.html:
<div ng-app='myApp' ng-controller='myController'>
<foo bar='bar'></foo>
</div>
app.js:
angular.module('myApp', ['templates']);
angular.module('myApp', ['templates']).directive('foo', function(){
return {
restrict: 'AE',
scope: {
bar: '='
},
templateUrl: 'bar.html'
}
});
angular.module('myApp').controller('myController', function($scope, $http){
$scope.bar = "XMan";
});
bar.html:
<h1> Hi {{ bar }}! </h1>
<ng-include src="'{{bar}}.html'"
XMan.html:
<p>Hello I'm XMan</p>
Here I am expecting my foo directive to render
<h1> Hi X Man! </h1>
<p> Hello I'm XMan </p>
but I am getting
<h1> Hi {{ bar }}! </h1>
<!-- ngInclude: undefined -->
What is wrong with my approach. Please guide me; I am very new to Angular.js.
I got a solution. We cannot bind ng-include src with scope variable.
Instead I used function call to get the source then it works!
That is I changed
<ng-include src="'{{bar}}.html'"
to
<ng-include src="barUrl()"
and added a controller scope function:
$scope.barUrl = function(){
return $scope.bar + '.html'
}

How to config routeProvider with MVC4 and WebAPI2

I have a small app that shows a calendar with some events.
When I click on one of the events I would like to show details of the selection below the calendar.
The events' urls are generated within a loop like this :
'url': '#/concerts/' + data[idx].id
and my config is the following:
var app = angular.module('EventsApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/concerts/:eventId', {
templateUrl: '/Views/Home/ng-view/details.html',
controller: 'EventCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
My Index.cshtml:
<div id="bodyApp" ng-app="EventsApp">
<div class="mainBody" ng-controller="EventCtrl as event" ng-init="event.getAllConcerts()">
<div class="search">
<input type="search" />
</div>
<div class="calendar">
<div id="calendar">
</div>
</div>
<div class="crudSection" ng-view>
</div>
</div>
At the moment I am just trying to get the details.html to be shown, but It doesn't redirect. The url is updated with the proper one but my view is not refreshed.
Also, How should the routeProvider config to do a webapi call without exposing the '/api/{controller}/{id}' info?
Edit.: I tried with the standard MVC route '/Home/{action} and a partialview and it works, but not a '/Home/{action}/{id}', so I think I'm missing something about how to combine both routings.
I found the solution in the following link:
AngularJS - How to use $routeParams in generating the templateUrl?
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/concerts/:eventId', {
templateUrl: function (params) { return '/Home/Details/' + params.eventId; },
controller: 'EventCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);

angularJS with MVC call - how to do something other than CRUD?

I've been following web tutorials to try to learn angularJS on a .NET MVC Application. All the tutorials seem to cover getting a list, getting an individual item etc.
What I want to do is allow the user to fill in an email address, I want to verify that email address against the database and return true or false if it existed. I'm then trying to put that value in the scope so I can do something in response to whether its true or false.
I'm using a single page app so this is the login html.
<form name="form" class="form-horizontal">
<div class="control-group" ng-class="{error: form.ValidEmailAddress.$invalid}">
<label class="control-label" for="ValidEmailAddress">Valid Email Address</label>
<div class="controls">
<input type="email" ng-model="item.ValidEmailAddress" id="ValidEmailAddress">
</div>
</div>
<div class="form-actions">
<button ng-click="login()" class="btn btn-primary">
Go!
</button>
<label ng-if="user.isAuthorised">Authorised</label>
<label ng-if="!user.isAuthorised">NotAuthorised</label>
</div>
</form>
In my app.js file I declare a loginCtrl controller when the url was /login so that's all fine. The logic that I'm calling on my button click is this:
var LoginCtrl = function ($scope, $location, $http, AuthorisedUser) {
$scope.login = function() {
var isValidUser = $http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress);
$scope.user.isAuthorised = isValidUser;
} };
Which is then calling an MVC AuthorisedUserController class method:
public bool IsValidUser(string id)
{
var list = ((IObjectContextAdapter)db).ObjectContext.CreateObjectSet<ApprovedUser>();
var anyItems = list.Any(u => u.ValidEmailAddress == id);
return anyItems;
}
So it vaguely seemed to be working when I put in a value like "aaa" into the textbox. But as soon I try putting in an email address the value is undefined. Maybe I'm supposed to be doing a post but the only thing I can successfully hit my .NET controller with is by using get.
I'm sure I'm missing fundamental knowledge and potentially tackling this in the wrong way.
In case it helps I've created a module and defined factories like this:
var EventsCalendarApp = angular.module("EventsCalendarApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/login', { controller: LoginCtrl, templateUrl: 'login.html', login: true }).
otherwise({ redirectTo: '/' });
});
EventsCalendarApp.factory('AuthorisedUser', function ($resource) {
return $resource('/api/AuthorisedUser/:id', { id: '#id' }, { isValidUser: { method: 'GET' } });
});
One of my questions is - should I be accessing the controller method using the $http object, or is there a way of using my factory declaration so that I can go something like:
AuthorisedUser.IsValidUser($scope.item.validEmailAddress)
I know in the tutorial I was following I could do stuff like:
CalendarEvent.save()
to be able to call a CalendarEventController post method.
What i think is, your get() function will return a promise. and you can't assign promise like this. so better try this approch once. I hope, it'd work. if not please let me know...
here I assume your first,second and third snippet of code works fine...
$http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress).success(function (result, status) {
var isValidUser=result;
$scope.user.isAuthorised = isValidUser;
$scope.$apply();
}).error(function (result, status) {
//put some error msg
});

Routing with angularjs in Mvc application

I have been continously trying to implement routing in Angularjs with Mvc 4.0 project but I am not able to do it.
I have created a empty MVC 4.0 project and added a controller "HomeController". Then I added a folder in Views with name Home having three views. One is index which opens when we run application as in route config we have route for homecontroller and Index Action.So, basically assuming the index page as the main page in Singlepage application, I have defined some code in the index page as given in 6oish book enter link description here.
Index. CShtml
#{
ViewBag.Title = "Index";
}
<style>
.container {
float: left;
width: 100%;
}
</style>
<script src="~/Scripts/angular.min.js"></script>
<h2>Practising Angular</h2>
List
Edit
<div ng-app="demoApp">
<div class="container">
<div ng-view=""></div>
</div>
</div>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'SimpleController', templateUrl: 'Home/List' })
.when('/Edit', { controller: 'SimpleController', templateUrl: 'Home/Edit' })
.otherwise({ redirectTo: '/' });
});
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [{ name: 'Dave jones', city: 'Phoenix' },
{ name: 'Jhon Dena', city: 'Mexico' },
{ name: 'Bradshaw', city: 'WashingTon' },
{ name: 'Rey Mysterio', city: 'Brazil' },
{ name: 'Randy', city: 'California' }, ];
});
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city })
};
</script>
Now, I need two more Views which are defined in the above route and they are as follows:
List.cshtml
#{
ViewBag.Title = "List";
}
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="objCust in customers | filter:filter.name">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
Customer Name:<br />
<input type="text" ng-model="newCustomer.name" /><br />
Customer city:<br />
<input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addcustomer()">Add customer</button>
</div>
and Last one is
Edit.cshtml
#{
ViewBag.Title = "Edit";
}
<h2>Edit the particular user. Things are under construction</h2>
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="city" />
<ul>
<li ng-repeat="objCust in customers | filter:city">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
</div>
Here is the home controller
namespace Routing_Angular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult List()
{
return PartialView();
}
public ActionResult Edit()
{
return PartialView();
}
}
}
I am attaching a image to show the Project structure.
I ma running the application, I can see the empty page where it is written "Practising Angular" with two anchor tags "List" and "Edit". I am not getting any change on changing the url.I added "/" in the url and It is not changed . then I added a "/Edit". then also I found no change. I have added anchor tags at the top in index page then also there is no change. only url gets changed. Please guide me where I am doing wrong.
There are a few things you need to fix in your views and angular code.
First of all, when defining the SimpleController, you have defined the addCustomer function outside the controller.
You should have the following controller definition:
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [{ name: 'Dave jones', city: 'Phoenix' },
{ name: 'Jhon Dena', city: 'Mexico' },
{ name: 'Bradshaw', city: 'WashingTon' },
{ name: 'Rey Mysterio', city: 'Brazil' },
{ name: 'Randy', city: 'California' }, ];
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });
};
});
Then in your list view, the function declared for the "Add Customer" button is wrong, as it is case sensitive. You should have addCustomer instead of addcustomer (with capital C, as defined in your SimpleController):
<button ng-click="addCustomer()">Add customer</button>
Also, I am not sure which version of angular you are using, but from version 1.2.0, routing needs to be loaded as a separate module (see this error). You can install it following these instructions, adding the script angular-route.min.js and declaring your module as:
var demoApp = angular.module('demoApp', ['ngRoute']);
You will know that you need to load the routing module because you will see an exception in the browser console when the initial Index view loads. (It's always a good idea to check the browser console for JS errors anyway)
That should be everything, hope it helps!

ASP.NET MVC and AngularJS

I am using AngularJS 1.2.2 (and am totally new to it) and MVC 5. I am trying to get a controller get called but it is not working.
As far as I could tell, the most appropriate 'shell' page is Views/Shared/_Layout.cshtml.
Therefore, in this page I have
<html data-ng-app="myApp">
Latter on in the Views/Shared/_Layout.cshtml I have
<div class="navbar navbar-fixed-top">
<div class="container">
<ul class="nav nav-pills" data-ng-controller="NavbarController">
<li data-ng-class="{'active':getClass('/home')}">Home</li>
<li data-ng-class="{'active':getClass('/albums')}">Albums</li>
</ul>
</div>
</div>
But when I click on either of these two links my getClass method does not get called. The file containing this method is being refernced. Here is the code it contains
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return true;
} else {
return false;
}
};
});
Any idea why this is not being called?
EDIT
My structure is such:
I have an app folder in the root.
In the app folder I have an app.js with this code
var app = angular.module('myApp', []);
app.config(function ($routeProvider) {
$routeProvider
.when('/Home',
{
controller: 'HomeController',
templateUrl: '/Views/Home/Index.cshtml'
})
.when('/Album',
{
controller: 'AlbumController',
templateUrl: '/View/Album/Index.cshtml'
})
.otherwise({ redirectTo: '/Home' });
});
(Incidentally I am guessing that by referring to my individual cshtml files like this I will get the correct behavior).
I have a controllers folder with the above NavbarController class.
I also have a services folder with my services in them.
In the _Layout file I have these js files referenced
#Scripts.Render("~/Scripts/angular.js")
#Scripts.Render("~/Scripts/angular-route.js")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
#Scripts.Render("~/app/app.js")
#Scripts.Render("~/app/controllers/navbarController.js")
#Scripts.Render("~/app/controllers/albumController.js")
#Scripts.Render("~/app/services/albumService.js")
There is an error in the console. It is
Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:unpr] Unknown provider: $routeProvider http://errors.angularjs.org/1.2.2/$injector/unpr?p0=%24routeProvider ...
It looks like you missed to include the ngRoute module in your dependency for myApp.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
//Your code
}]);

Resources