Hyperlinks with Angular Route / MVC Area not working - angularjs

I have a bit of a complicated MVC project that we are adding some Angular capability to. I am very new to Angular and have watch three Angular courses on Pluralsight now. They have been very helpful but I am missing some piece of understanding.
I understand that I need to have just one ng-app (unless I want to bootstrap and I don't think I want to). So this app has defined my config and a custom directive. The custom directive is working nicely but when I click on a link in that directive it does not go anywhere....well perhaps it does but not where I am expecting. Fiddler shows nothing unusual like 404 or 500 errors.
(function ()
{
"use-strict";
angular.module("appMainNav", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider.when("/MySearch", {
controller: "routingController"
});
$routeProvider.otherwise({ redirectTo: "/" });
})
})();
My routingController:
(function () {
"use strict";
angular.module("appMainNav")
.controller("routingController", routingController);
function routingController($http) {
var vm = this;
alert("Routed");
}
})();
My HTML link as rendered:
Search
I don't get a page not found...the url just appends the #/MySearch. No console errors etc.
I was expecting to get a javascript alert...?
TIA
Edit
Should have added sooner. Here is markup:
_Layout page:
<body>
<div ng-app="appMainNav" ng-controller="routingController" class="container">
#RenderBody()
</div>
</body>
RenderBody is Index.cshtml:
<div class="row">
<div>
Header Stuff
</div>
</div>
<div class="row">
<div class="col-md-2">
<dashboard-main-nav></dashboard-main-nav>
</div>
<div class="col-md-3">
<div></div>
</div>
<div class="col-md-8">
<div></div>
</div>
</div>
<div class="row">
<div>
Footer Stuff
</div>
</div>
The custom directive angular code was left out of the snips above however that is where the link is generated.

You need to assign an event handler to a click event on the anchor tag:
Search
where foo is a function defined on the controller's scope:
function routingController($http, $scope) {
var vm = this;
$scope.foo = function(){
alert("I am so tired");
}
alert("Routed");
}
Try that and it should work.

Related

ui-router Main View is rendering thrice and no controller are registering

I am trying to create a SPA using angular ui-router with MVC. I am facing three issues.
1.The controllers OfferController.js and OfferCustomizationController.js are not registering.
2.I am getting the errors ' No reference point given for path '.offer', No reference point given for path '.customizations'.
3. Main view is rendering thrice.
I have no clue what am i missing. Please help.
I have included the following files in my Layout.cshtml:
<script src="#Links.Scripts.angular_min_js"></script>
<script src="#Links.Scripts.ProductCatalog.app_js"></script>
<script src="#Links.Scripts.ProductCatalog.service_js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
I have made two views. Offers And OfferCustomizations. And a main view. Following is my code for the main view:
<div class="inside-data-div" ng-app="ProductCatalog">
#*<div ui-view></div>*#
<div class="col-lg-12">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div id="form-container">
<div class="page-header text-center">
<h2>Create Offer</h2>
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".offer"><span>1</span> Offer Details</a>
<a ui-sref-active="active" ui-sref=".customizations"><span>2</span> Offer Customizations</a>
</div>
</div>
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="SaveForm()">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
</div>
<!-- show our formData as it is being typed -->
<pre>
{{ formData }}
</pre>
</div>
</div>
</div>
</div>
Following is my code of app js:
var productCatalogApp = angular.module('ProductCatalog', ['ui.router']);
productCatalogApp.value('appName', 'Product Catalog');
productCatalogApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('wizard', {
url: '/wizard',
templateUrl: 'WizardSubForm',
controller: 'WizardMainController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('wizard.offer', {
url: '/offer',
templateUrl: 'OfferForm',
controller: 'OfferCtrlr'
})
// url will be /form/interests
.state('wizard.customizations', {
url: '/customizations',
templateUrl: 'OfferCustomizations',
controller: 'CustomizationCtrlr'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/wizard/offer');
});
productCatalogApp.controller('WizardMainController', function ($scope) {
// we will store all of our form data in this object
$scope.formData = {};
// function to process the form
$scope.SaveForm = function () {
alert('awesome!');
$scope.formData = { "Offer": $scope.offer, QuestionGroups: $scope.QuestionGroups }
};
});
This is how i'm registering my controllers. Below is the one for offercontroller.
var app = angular.module('ProductCatalog.controllers', []);
app.controller('OfferCtrlr', function ($scope, $http, $modal) {
});
Any help will be appreciated.

Several (multi) functions of the controller AngularJS

I want to use several functions in one controller. First family makes a request, the second part of the page should display by pressing the button (as here http://www.w3schools.com/angular/tryit.asp?filename=try_ng_events_toggle).
The first function is working fine, but the second is not.
app.controller('DemoCtrl', function($http) {},function($scope){})
This is the second function of the controller:
function($scope){
$scope.showMe=false;
$scope.myFunc=function() {
$scope.showMe=!$scope.showMe;
}
As planned at the touch of a button should show the page:
``
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as vm">
<button ng-click="myFunc()">Click Me!</button>
<div ng-show=vm.showMe>
<h1>Menu:</h1>
<div>Pizza</div>
<div>Pasta</div>
<div>Pesce</div>
</div>
</div>
`
Sourse:http://zalil.su/3296697
angular controller takes one function with all dependencies.
app.controller('DemoCtrl', function($http,$scope) {
$scope.showMe=false;
$scope.myFunc=function() {
$scope.showMe=!$scope.showMe;
}
$scope.makeAjax= function(){
$http.something()...
}
})
got through this link https://docs.angularjs.org/guide/controller

bind controller on dynamic HTML

I have a HTML page with different sections, which are loaded with AJAX. I have created a controller for each of the sections.
How is possible to bind the controller on a section which has been dynamically added on HTML?
I have found very complicated solutions, which i don't even know if they apply.
I need the most basic, easiest solution, something similiar with ko.applyBindings($dom[0], viewModel) for the ones who worked with KnockoutJs.
Index html
<div class="row" ng-app="app">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked">
<li>
Profile
</li>
</ul>
</div>
<div class="col-xs-9">
<div id="container"><!-- load dynamic HTML here --></div>
</div>
</div>
Dynamic HTML
<div ng-controller="profile">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
Javascript:
var app = angular.module('app', []);
app.controller('profile', function ($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
// load new HTML
// normally this is triggered by a link / button
$(function () {
$.get("/EditProfile/Profile", function (data, status) {
$("#container").html(data);
});
});
Don't use jQuery to embed html to your container. If you use jQuery, AngularJS can't track DOM manipulations and trigger directives. You can use ng-include directive of AngularJS.
In index.html file:
...
<div id="container">
<div ng-include="'/EditProfile/Profile'"></div>
</div>
...
If you want you can make that conditional:
...
<div id="container">
<div ng-if="profilePage" ng-include="'/EditProfile/Profile'"></div>
</div>
...
With that example, if you set profilePage variable to true, profile html will be load and render by ng-include.
For detailed info take a look to ngInclude documentation.
By the way, best practice to include views to your layout by triggering same link clicks is using routers. You can use Angular's ngRoute module or uiRouter as another popular one.
If you use ngRoute module, your index.html looks like that:
<div class="row" ng-app="app">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked">
<li>
Profile
</li>
</ul>
</div>
<div class="col-xs-9">
<div id="container" ng-view><!-- load dynamic HTML here --></div>
</div>
</div>
And with a router configuration like below, profile html will be automatically loaded and rendered by ngRoute inside ngView directive:
angular.module('myapp', []).config(function($routeProvider) {
$routeProvider
.when('/profile', {
templateUrl: '/EditProfile/Profile',
controller: 'ProfileController'
});
});

Angular Bootstrap collapse not firing even though $scope says it should

Angular newbie here, running Angular 1.3 & ui-bootstrap 0.12. I'm just trying to learn Angular and ui-bootstrap and am unsure why the Angular Bootstrap collapse directive is not collapsing my div. Clicking on the buttons correctly toggles $scope.rightPanelCollapse yet the collapse is not happening.
Here's my markup:
<body ng-app="uxf.site">
<div class="container-fluid" data-ng-controller="UxfSiteController">
<button data-ng-click="toggleRightPanelCollapse()">{{rightPanelCollapse}}</button>
<button data-ng-click="toggleRightPanelCollapse()">{{rightPanelCollapse}}</button>
<div class="row">
<div id="left-panel" class="col-md-1 grid">
{{rightPanelCollapse}}
</div>
<div id="content" class="col-md-10 col grid">
{{rightPanelCollapse}}
</div>
<div id="right-panel" collapse="rightPanelCollapse">
{{rightPanelCollapse}}
</div>
</div>
</div>
Here's my JS:
(function(angular) {
'use strict';
angular.module('uxf.site', [])
.controller('UxfSiteController', ['$scope', function($scope) {
$scope.rightPanelCollapse = true;
$scope.toggleRightPanelCollapse = function() {
$scope.rightPanelCollapse = !$scope.rightPanelCollapse;
};
}]);
})(window.angular);
...newbie move. I just forget to add ui.bootstrap.collapse as a dependency in my uxf.site module. Problem solved.

Why isn't the Angular ng-click event firing?

I've been following a course to learn angularjs and I can't seem to get a simple ng-click binding to work.
HTML:
<body ng-controller="MainController">
<div ng-app="githubViewer">
<h1>{{message}}</h1>
<div>{{ error }}</div>
{{username}}
<form name="searchUser">
<input type="search" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
<div>
<div>{{user.name}}</div>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}">
{{user.gravatar_id}}
</div>
</div>
</body>
Javascript:
(function () {
var module = angular.module("githubViewer", []);
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
};
var onError = function (reason) {
$scope.error = "Could not fetch the user";
$scope.reason = reason;
};
$scope.username = "angular";
$scope.message = "Github Viewer";
$scope.search = function (username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
};
module.controller("MainController", MainController);
}());
When you click the search button (search for username "odetocode" or "robconery") it is supposed to display an image but the click event does not seem to be firing. I have searched the documentation and looked over the course again but I can't see what I'm doing wrong.
I'm currently using version 1.2.16 of angularjs.
You have the ng-controller declaration outside of the ng-app declaration right now:
<body ng-controller="MainController">
<div ng-app="githubViewer">
It should be the other way around, or have both on the same element
<body ng-app="githubViewer" ng-controller="MainController">
<div>
AngularJS evaluates your code, and checks for any directives you have declared from the ng-app element down, including the element it is declared on; This currently is missing the ng-controller directive, as it is placed on a parent element of the ng-app element.
You need to put the controller within the context of the module to have it within its scope.
Like so
<body ng-app="githubViewer" ng-controller="MainController">
Demo here

Resources