Dynamically add content in Angular with ajax - javascript

I have a page on a website based on AngularJS on which content gets loaded via ajax into a div. My problem is that the Angular directives in the loaded content and the controller seem to get ignored. How can I make the controller working?
HMTL:
Load Content
<div id="myForm-con">
</div>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>
<script type="text/javascript">
$('#loadContent').on('click', function() {
$.post("load-my-form.php", function(data, result) {
$('#myForm-con').html(data);
});
});
</script>
app.js
(function() {
var app = angular.module('app', []);
app.controller('validationCtrl', ['$scope',
function ($scope) {
$scope.submitForm = function () {
$scope.submitted = true;
if ($scope.myForm.$valid) {
alert('form is valid');
}
}
}
]);
})();
HTML ajax loaded form
<div ng-controller="validationCtrl">
<form id="my-form" name="myForm" ng-submit="submitForm()" novalidate>
...
</form>
</div>

I'd probably try something like this:
HTML
Load Content
Angular
$scope.loadContent() = $http.post("load-my-form.php", data).then(function (result) {
$('#myForm-con').html(result);
});
Or alternatively
Angular
$scope.formResults = '';
$scope.loadContent() = $http.post("load-my-form.php", data).then(function (result) {
$scope.formResults = result;
});
HTML
<div id="myForm-con">{{formResults}}</div>

In order for this to work you have to do 2 things:
1 - use angular http and .then for the callback -
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
2- use angular data-binding to link your data to a view, for example - 2-ways data-binding.

Related

MVC view button click event , Pass AngularJs object to another MVC Controller

I have to pass AngularJs object to another Controller when button click event on view.
CHTML
<div ng-repeat="hotel in respData.hotels">
<button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability
</button></div>
Script
$scope.setTab = function (hotelcode) {
var url = 'Hotel';
url += '?HotelCode=' + hotelcode '
window.location.href = url;}
Now i'm passing one value only. I want to pass hotel object as a parameter.
Is their way to do that?
You can pass your whole Hotel object to your first controller and then make use of $emit or $broadcast in order to send that object to another controller. Here's a short example:
One.html
<html ng-app="app">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script>
var app = angular.module('app', ['ui.router']).config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('two',{
url: '/two',
templateUrl: "two.html",
})
})
app.controller("Parent", function ($scope, $state) {
$scope.send = function (msg) {
$scope.$broadcast('eventName', { message: msg });
$state.go('two')
};
});
app.controller("Child", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
</script>
<body ng-app="app">
<h1> Index Page </h1>
<!---
Look at these div tags here, $broadcast is used to transfer content from
Parent to Child Controllers only and $emit for Child to Parent Controller
!--->
<div ng-controller = "Parent" >
<button ng-click = send('Hello')> Send Hello</button>
<div ng-controller = "Child" class="container" ui-view> </div>
</div>
</body>
</html>
Two.html
<body ng-app="app">
<span> Recieved : {{message}}</span>
</body>
$state.go('toState',object);
You can use $state.go to send object values to another controller if you are using ui-router if not you can use emit and broadcast see details here
Working plnkr of broadcast can be found here
app.controller('Parent', function($scope) {
$scope.message="";
$scope.emitedmessage="";
$scope.clickevent=function(){
$scope.$broadcast('transfer',{message:$scope.message});
}
$scope.$on('transferUp',function(event,data){
console.log('on working');
$scope.emitedmessage=data.message;
});
});
app.controller('Child',function($scope){
$scope.message="";
$scope.broadcastmessage=""
$scope.$on('transfer',function(event,data){
$scope.broadcastmessage=data.message;
});
$scope.clickevent=function(){
$scope.$emit('transferUp',{message:$scope.message});
}
});

Calling anonymous method recursively in angular controller method

I want to send ajax requests at regular intervals from the angular controller method. for that i have written code like below.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$timeout) {
$('#radioBtn a').on('click', function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
$timeout(function(){
//how to call the anonymous function passed to $('#radioBtn a').on() here.
},30000);
});
I am not getting how to call the anonymous method from timeout function. Using this() is failing.
First off: Don't bind to element clicks like that, use the ng-click directive - in fact, just don't even load jQuery in your application, in 99% cases you're better off without it.
Second: Use angular's $interval service. Check the code sample below.
angular.module('app', [])
.controller('ctrl', function($scope, $interval) {
$scope.numbers = [];
$scope.startInterval = function() {
$scope.interval = $interval(function() {
$scope.numbers.push($scope.numbers.length);
}, 1000)
}
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl">
<button ng-if="!interval" ng-click="startInterval()">Start polling</button>
<div ng-repeat="number in numbers">
{{number}}
</div>
</body>
</html>
try this way.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$interval) {
$('#radioBtn a').on('click', function(){
$interval(function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
},30000);
});

REST call in AngularJS does not display record

This is my first AngularJS project. I followed this website to create a simple html to display a single record by calling restful services. The rest works with the url "http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009".
Here is my html:
<html ng-app="cgApp" ng-controller="CgseqCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
<body>
<div>
<hr>
<h2>{{seq.analysisId}}</h2>
<h2>{{seq.library}}</h2>
</hr>
</div>
</body>
</html>
I defined the resource in a service js
//service.js
angular.module('cgApp', ['ngResource'])
.factory('CgseqService', function ($resource) {
return $resource('http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009',
{get: {method: 'GET'}
});
});
The controller:
//controller.js
angular.module('cgApp', ['ngResource'])
.controller('CgseqCtrl', ['CgseqService', '$scope', function (CgseqService, $scope)
{
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
}]);
When I started my http server with Node.js and typed the url in the browser, nothing is displayed. What did I do wrong?
Several errors.
You didn't load your factory code. It looks like you only loaded your controller.js (I'm assuming your factory code is in a different file since in your example you commented it as //service.js):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
np-controller should say ng-controller:
<html ng-app="cgApp" np-controller="CgseqCtrl">
You also never called your $scope.getSeq function:
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
You should call $scope.getSeq() somewhere to actually invoke it.

How to use onload attribute with ng-controller directive to execute a function defined within the controller?

I have to call the submit() function the moment the page loads. However this sort of arrangement gives a submit() method not found error. I am unable to understand the placement of ng-controller and onload.
Also if there is any alternative way of doing this with angular, please point that out as well.
PS: This is a code snippet. All variables have been defined.
<body ng-controller="DashboardDisplay" onload="submit()">
<div class="container-fluid" >
{{scope.arr}}
</div>
</body>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('DashboardDisplay', ['$scope','$http',function($scope,$http) {
$scope.submit = function(){
var jsonOb = {"A":"B"};
$http.post(URL,jsonOb).
success(function(response) {
console.log('got it' + response);
$scope.arr=response;
}).
error(function(data, status, headers, config) {
console.log('nufin' + status);
});
}
}]);
Use ng-init instead of onload i.e
<body ng-controller="DashboardDisplay" ng-init="submit()">
And removed scope which before arr in html i.e
{{scope.arr}} to {{arr}}
I have created working DEMO
https://jsfiddle.net/Shital_D/x2k8n23n/1/

AngularJS two controllers... overcoming $scope.$on when page loads

Still wrapping my head around AngularJS. I have a pretty basic page which has two controllers. One has text input to take tags (for searching). The other calls http.get(), using the tags to get the images... it does a bit of ordering and then they're displayed. Following some info on the page below, I came up w/ something.
Can one controller call another?
Caveat: It requires onClick() to execute. Generally I want it to load up on page load with zero tags... and after a click with the tags. I've seen a few suggestions in other threads here, but I'm not quite sure how to pull them off in this case. imagesController runs on load, but of course doesn't get past the 'handleBroadcast' bit.
var myModule = angular.module('myModule', []);
myModule.run(function($rootScope) {
$rootScope.$on('handleEmit', function(event, args) {
$rootScope.$broadcast('handleBroadcast', args);
});
});
function tagsController($scope) {
$scope.handleClick = function(msg) {
$scope.tags = msg;
$scope.$emit( 'handleEmit', { tags: msg });
};
}
function imagesController($scope,$http) {
$scope.$on('handleBroadcast', function(event, args) {
$scope.tags = args.tags;
var site = "http://www.example.com";
var page = "/images.php";
if ( args.tags ) {
page += "?tags=" + $scope.tags;
}
$http.get(site+page).success( function(response) {
// SNIP
$scope.data = response;
});
});
}
The HTML is quite trivial. Slightly simplified, but it should suffice.
<form name="myForm" ng-controller="tagsController">
<div class="left_column">
<input class="textbox_styled" name="input" data-ng-model="tags"><br>
<button ng-click="handleClick(tags);">Search</button><br>
</div>
</form>
<div class="centered" data-ng-controller="imagesController">
<span class="" data-ng-repeat="x in data">
{{x}}
</span>
</div>
Not sure I fully understood, but if you want to show it with no tags on load, simply emit the event when the controller loads:
function tagsController($scope) {
$scope.handleClick = function(msg) {
$scope.tags = msg;
$scope.$emit( 'handleEmit', { tags: msg });
};
$scope.$emit( 'handleEmit', { tags: "" }); // or $scope.handleClick("");
}

Categories

Resources