I have a series of html files I am including into my main controller. These html files are not actually being used for atleast 4 seconds while one html file does its stuff. How would I define to delay loading of rest of the files to improve startup performance of the app.
<div ng-app="myApp" ng-controller="myController" >
<div ng-include="somefile.html" ></div>
<!-- More files to include -->
</div>
Another solution(less elegant) could be:
<div ng-app="myApp" ng-controller="myController" >
<div ng-include="template" ></div>
<!-- More files to include -->
</div>
In your controller initialize template with
$scope.template = '';
And do
$scope.template = 'somefile.html';
when you need the template to be loaded.
Load these asynchron with promises. This covers the idea:
var promise = $http.get('someFile.html').success(function (data) {
htmlContent = data.response;
});
promise.then(function(result) {
$scope.model = result;
});
Related
I want to use AngularJS code inside bootstrap modal i am loading the bootstrap modal with Jquery code
and after loading the modal i want to use angular JS code to fetch and insert data.The angular code is working fine in seperate view but when i tried to use it in modal i am getting angular js warning of
Tried to load angular more than once in bootstrap modal.How can i successfully get this working.
Here is my code
<script type="text/javascript">
$(document).ready(function () {
$('.className').on('click', function () {
$.get('url', { id: id, mid: mid }, function (data) {
$('#detail').html(data);
$('#modal').modal('show');
});
});
});
</script>
In Bootstrap modal i have following code
#model Model
<div class="modal-lg modal-dialog" role="document">
<div class="modal-content panel panel-info">
<div class="modal-header panel-heading">
<a class="close" data-dismiss="modal">×</a>
</div>
<div ng-app="MyApp">
<div ng-controller="MyController">
<div class="modal-body panel-body">
<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
//TO Show Data
</table>
<table border="0" cellpadding="0" cellspacing="0">
//Form to insert data
</table>
</div>
</div>
</div>
</div>
</div>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.btntext = "Save";
$scope.Savedata = function () {
//For Saving
}
$http.get("url").then(function (data) {
//For fetching data
});
</script>
The html control through which i am loading the modal is inside another partial view
so i have main view inside that one partial view and from that i am loading the modal which is also a partial view.
Can anybody help me
I think the error code tells you that you already have angular loaded - thus you can use it inside modal without load it again
I guess you have reference to angular library in more than one place
Web project: backend - ASP.NET, frontend - AngularJS.
I have the "main page" with mainApp module.
Also i have the another page with the registration, which is the responsibility of LoginLayerApp.
What i want: when you click on "main window" i need pop-up window with the registration content (html, css, angularController and so on).
What was tried:
Loaded using JQuery, implement the DOM and call angular.bootstrap by
hands.
Loaded via $http and using ngDialog library to open a pop-up
window.
Use the iframe.
The problem is that the loaded naked HTML, but I do not know how to inject LoginLayerApp, to then rebuild the naked HTML. I can do it only once, but not as usual, when angular always rebuild view by changes in controller (for example, different ng-class depending on the width of the screen).
How to do the most right? Perhaps I should do differently to organize something?
RequireJS, WebPack will not work, too much legacy-project implementation for such a trifle.
Example of registration page:
#using Inventum.ViewModels.Account
#using Microsoft.Owin.Security
#{
Layout = null;
}
<link href="~/Content/css/layers/Login/loginRegistrationLayer.min.css" rel="stylesheet" />
<div ng-app="loginLayerApp"
ng-controller="loginLayerController as loginCtrl"
ng-init="init(); returnUrl = '#ViewBag.ReturnUrl'; type = ('#ViewBag.Type' == '') ? 'login' : '#ViewBag.Type'; form={}; user={};"
esc-key="closeLayer()"
class="login-app-container"
tabindex="0">
<div class="container" ng-class="{'mobile': !desktop, 'desktop': desktop }" ng-switch on="type">
<!-- =============== LOGIN =============== -->
<div class="registration-container" ng-switch-when="login">
{{loginCtrl.desktop}}
{{desktop}}
<h1>#Html.ClickZone("NewRegLogin.Login.Title")</h1>
<div class="main-label">
<span>#Html.ClickZone("NewRegLogin.Login.HelpLabel")</span>
<br ng-show="phoneBreakpoint">
</div>
<!-- ======== Errors block ======== -->
<!-- ======== Errors block ======== -->
<div class="options">
<ng-form name="form.userForm" ng-class="{'showMe': nosocial && !desktop}" novalidate enter-key="trySubmit = true; submitForm(form.userForm.$valid, user)">
<!-- <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> -->
<div class="emailFocusHandler" ng-hide="desktop || nosocial" ng-click="nosocial = true;"></div>
<div class="group">
</div>
<div ng-show="desktop || nosocial">
<div class="group">
</div>
<div class="help-buttons">
</div>
<div class="error-block" ng-if="loginFailed && answerCode == ANSWERS.LOGIN.UserNoutFound">
</div>
<button type="submit" ng-click="trySubmit = true; submitForm(form.userForm.$valid, user)">#Html.ClickZone("NewRegLogin.SignIn") </button>
</div>
</ng-form>
<div class="delimeter" ng-show="desktop || nosocial"></div>
</div>
</div>
<!-- =============== LOGIN =============== -->
</div>
#section scripts {
<!-- ANGULARJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.min.js"></script>
#Scripts.Render("~/bundles/js/layer/newLogin")
<script src="https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit" async defer></script>
}
What I would do is create the modal window (pop-up window) as a angular-ui modal. (their modal docs). That way you don't have to write your own modal code.
When you implement it, the modal will get its own controller and its own html file and the implementation will look like this:
Current Controller-
appName.controller('loginLayerController', ["$scope","uibModal", function ($scope, $uibModal){
$scope.openComponentModal = function () {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'myModalController',
controllerAs: 'myModalController'
}
});
}])
And from there you can put your form into myModalContent.html, and hide and show buttons there accordingly
I'm not sure, but you can try to create component, that will show your errors. By default set in invisible. In controllers you can manage how many and when you should show your error messages.
any help about who insert html with Angular code inside the html string.
Example:
<div class="container">
<span class='btn' onclick="javascript: clicklink()">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
function clicklink(){
$("#content").html("<span class='label label-danger'>Invoice</span>"+
" <div ng-app ng-init='qty=1;cost=2'> <b>Total:</b> {{qty * cost | currency}} </div>");
}
</script>
Example click here
If you're looking for a 'Hello World' kind of example, this is probably as basic as it gets.
https://code-maven.com/hello-world-with-angular-controller
Maybe the example doesn't make sense, but here is the thing maybe exist another way to do that. I have a project with c# MVC and for render some Views I use ajax
Javascript to load modal into View:
function Edit(){
$.ajax({
url: '../Controller_/Action_',
type: 'POST',
datatype: "html",
traditional: true,
data: { data1: data1 },
success: function (result) {
$('._container').html(result);
},
error: function (result) { }
});
}
MVC c# code:
public ActionResult Edit()
{
...\ code \...
return PartialView("/View/_Edit", model);
}
View Main:
Open Modal
<div name="_container">
<!-- Here load body of modal -->
</div>
Partial view (Edit) return by Action (Edit) in Controller . Should be a modal structure:
<div name="_editModal">
#html.LabelFor( x => x.Name)
#html.EditorFor( x => x.Name)
<div ng-app ng-init="qty=1;cost=2">
<b>Invoice:</b>
<div>
Quantity: <input type="number" min="0" ng-model="qty">
</div>
<div>
Costs: <input type="number" min="0" ng-model="cost">
</div>
<div>
<b>Total:</b> {{qty * cost | currency}}
</div>
</div>
</div>
As already stated by a bunch of people in the comments and other answers this is absolutely bad practice. But there is also a built-in option to solve your problem with pure AngularJS using $compile.
In order to make that work you need to place everything inside a controller or directive and inject the $compile service accordingly.
You need to use the $compile service to produce a function of your dynamic HTML markup which is able to consume a scope object as a parameter in order to produce a working AngularJS template.
After inserting your template, you need to trigger the AngularJS digest cycle using $apply.
<div class="container" ng-controller="MyController">
<span class='btn' ng-click="clicklink()"">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
app.controller("MyController", function($scope, $compile) {
var template = "<button ng-click='doSomething()'>{{label}}</button>";
$scope.clicklink = function(){
$scope.apply(function(){
var content = $compile(template)($scope);
$("#content").append(content);
});
}
});
</script>
I currently have this site - http://dev.5874.co.uk/scd-data/ where I have a dropdown which displays results from WP-API which I am pulling in through AngularJS.
It currently combines the two sets of results as they're separate URL's, the results are in categories within a custom post type so if both posts are 'tagged' in the same category chosen they display twice. I need a way to combine the two sets of results but only showing one of the posts - I hope this makes sense. I'm very new to API data and AngularJS and I imagine there is a much simpler way of doing this. Any help would be much appreciated. Here is a snippet of my code to show how it's currently working.
Thanks in advance!
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<style>
.desc {display: none;}
</style>
<script type="text/javascript">
$(function(){
$('.selectOption').change(function(){
var selected = $(this).find(':selected').text();
//alert(selected);
$(".desc").hide();
$('#' + selected).show();
}).change()
});
</script>
<script>
var app = angular.module('myApp', []);
app.controller('northWestCtrl', function($scope, $http) {
var url = 'http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northwest';
$http.get(url).then(function(data) {
$scope.data = data.data;
});
});
</script>
<select class="selectOption">
<option>Search by Region</option>
<option>NorthWest</option>
<option>NorthEast</option>
<option>Midlands</option>
<option>EastAnglia</option>
<option>SouthEast</option>
<option>SouthWest</option>
<option>Scotland</option>
<option>Wales</option>
<option>NorthernIreland</option>
<option>ChannelIslands</option>
</select>
<div id="changingArea">
<body ng-app="myApp">
<div id="NorthWest" class="desc">
<div ng-controller="northWestCtrl">
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<img src="{{d.acf.logo}}">
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
</div>
</div>
</body>
</div>
Here is a working code pen - http://codepen.io/anon/pen/yePYdq
Angular is a great JavaScript front-end framework to choose, and you're off to a good start, but a lot of changes could be made. I've made some suggested changes for easier ways to do things below.
See this CodePen for all changes.
It looks like you've grasped the idea of ng-repeat, but there's definitely a lot of repeated HTML and JS in your view and controller, so let's see if we can do better.
Let's try this without jQuery to avoid direct manipulation of the DOM. And instead of many controllers, we can do this with a single controller.
<div ng-app="MyApp">
<div ng-controller="MyController">
...
</div>
</div>
<script type="text/javascript">
var app = angular.module('MyApp', []);
app.controller('MyController', ...);
</script>
For the dropdown, we'll use ng-repeat in our view and display the names of the shooting types from our model
...
<select ng-model="selectedListing">
<option
ng-repeat="listingShootingType in listingShootingTypes"
value="{{listingShootingType.name}}">
{{listingShootingType.name}}
</option>
</select>
...
<script type="text/javascript">
...
// Our selections/filters
$scope.listingShootingTypes = [
'All',
'Air Rifle/Air Pistol',
'Clay',
'ABT',
'Double Trap',
'English Skeet',
'English Sporting',
'Fitasc',
'Olympic Skeet',
'Olympic Trap',
'Simulated Game',
'Sport Trap/Compact',
'Universal Trench',
'ZZ/Helice',
'Rifle',
'Centrefire Target Rifle',
'Gallery Rifle',
'Muzzle Loading',
'Practice Shotgun',
'Smallbore Rifle'
];
...
</script>
With only one controller, we can still use ng-repeat for each listing.
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<div id="listing-image"><img src="{{d.acf.logo}}"></div>
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
Finally... How do we only display listings that match our selected shooting type from the dropdown? We could use a custom Angular filter!
...
<div ng-repeat="d in data | filter:isSelectedListing">
...
<script type="text/javascript">
...
// Let's define a custom Angular filter because the WordPress JSON is complex
$scope.isSelectedListing = function(listing) {
// Show nothing if nothing is selected
if (angular.isUndefined($scope.selectedListing) || $scope.selectedListing == '') {
return false;
}
// Show all if 'All' is selected
if ($scope.selectedListing == 'All') {
return true;
}
// If the shooting type we're looking for is present, show the listing.
// To do this, we parse the WordPress JSON object model.
if (angular.isDefined(listing.terms.listing_shooting_type)) {
for (var i = 0; i < listing.terms.listing_shooting_type.length; i++) {
if (listing.terms.listing_shooting_type[i].name == $scope.selectedListing) {
return true;
}
}
}
return false;
};
...
</script>
Hopefully this gives you an idea of how we better leverage ng-repeat + DRY :)
The entire CodePen is here.
I am building a quick Angular app that uses a service to grab a JSON from a URL.
The JSON structure looks like this:
{news:[{title:"title",description:'decription'},
{title:"title",description:'decription'},
{title:"title",description:'decription'}
]};
What I need is just the array within the news object.
My code to import the JSON is as follows:
app.factory('getNews', ['$http', function($http) {
return $http.get('URL')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Then to add the data to the $scope object in the controller I do this:
app.controller('MainController', ['$scope','getNews', function($scope, getNews) {
getNews.success(function(data)) {
$scope.newsInfo = data.news;
});
});
But it doesn't work. When I load the html page, there is only white. My thinking is that this is because it isn't grabbing the array within the JSON and using that data to populate the HTML directive I set up.
newsInfo.js:
app.directive('newsInfo',function(){
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl:'newsInfo.html'
};
});
newsInfo.html:
<h2>{{ info.title }}</h2>
<p>{{ info.published }}</p>
My HTML doc is:
<head>
<title></title>
<!--src for AngularJS library-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<body ng-app="THE APP NAME"> <!--insert ng app here-->
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
<!-- Modules -->
<script src="app.js"></script>
<!-- Controllers -->
<script src="MainController.js"></script>
<!-- Services -->
<script src="getNews.js"></script>
<!-- Directives -->
<script src="newsInfo.js"></script>
</body>
Thoughts?
Change
<newsInfo info="news"></newsInfo>
to
<news-info info="news"></news-info>
example: https://jsfiddle.net/bhv0zvhw/3/
You haven't specified the controller.
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
$scope.getNews = function(){
return $http.get('URL').success(function(data) {
return data.news;
})
};
^ This, just change it so that the success function returns only the news!
While I am answering my own question, I should point out that everyone's answers were also correct. The code had multiple errors, but the final error was fixed by doing the following:
Apparently I had to upload the newsInfo.html doc to an S3 bucket and use that URL as “Cross origin requests are only supported for HTTP.” But then Angular blocked that external source with the Error: "$sce:insecurl Processing of a Resource from Untrusted Source Blocked".
So since the html template was so simple, i just bipassed this issue by typing in the template directly into the .js directive and it worked! thanks everyone for the help!