AngularJS, Async - ng-repeat not waiting for scope to be set - javascript

When I load up my index page, my ajax call works and the scope does get set. But it seems like ng-repeat is loading before the scope gets set with "products".
I feel like there should be a way to either
Load the page without having to wait for the scope to be set, but when it does get set - then re-run the loop "ng-repeat"
Wait for the AJAX Call to be done before initializing the loop ('ng-repeat')
Cheers!
products.controller.js
dvpModule.controller("ProductsController", function ($scope, productRepository) {
productRepository.get().then(function(products) {
$scope.products = products;
});
});
products-repository.js
dvpModule.factory('productRepository', function($http, $q) {
return {
get: function() {
var deferred = $q.defer();
$http({
method: 'POST',
url: 'http://localhost/test/wp-admin/admin-ajax.php',
params: { action: 'getAllProductUrls' },
}).success(deferred.resolve).error(deferred.reject);
return deferred.promise;
}
};
});
index.html
<html ng-app="dvpModule">
<head>
<script type='text/javascript' src='js/angular.min.js'></script>
<script src="js/scripts/dvp_module.js" /></script>
<script src="js/scripts/products-controller.js" /></script>
<script src="js/scripts/products-repository.js" /></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<title>DVP {{2 + 2}}</title>
</head>
<body ng-controller="ProductsController">
<div>
<tr ng-repeat="product in products">
<th>{{product.Category}}</th>
<th>{{product.Features}}</th>
<th>{{product.MODEL_SERIES}}</th>
</tr>
</div>

Related

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);
});

AngularJS call compile after compiled

<!DOCTYPE HTML>
<html lang="en-US" ng-app="theapp">
<head>
<meta charset="UTF-8">
<title>asd</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
var mainScope;
angular.module('theapp', []).controller('MainCtrl', function($scope, $injector) {
$scope.demo = "test123";
$scope.scopecomp = function(){
angular.element(document).injector().invoke(function ($compile) {
$compile(document.body)($scope);
});
}
mainScope = $scope;
});
function addDiv(){
var $newDiv = $('<div>{{demo}}</div>');
$(document.body).append($newDiv);
}
function comp(){
mainScope.comp();
}
</script>
</head>
<body ng-controller="MainCtrl" ng-change="comp();">
<h1>{{demo}}</h1>
<input type="text" id="compText" />
<button onclick="addDiv();">add</button>
<button ng-click="scopecomp();">compile with ng-click (works fine)</button>
<button onclick="comp();">compile with onlick (not working)</button>
</body>
</html>
I want to run the comp() function anywhere in my project. I tried button onclick,it didn't work but ng-click works fine. What is the problem ? Why onclick doesn't work ?
New : changeContent function added.
<!DOCTYPE HTML>
<html lang="en-US" ng-app="theapp">
<head ng-controller="MainCtrl as main">
<meta charset="UTF-8">
<title>asd</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
angular.module("theapp", []).controller("MainCtrl", MainController);
MainController.$injector = ['$timeout'];
var vm;
function MainController($timeout) {
vm = this;
vm.post = null;
function loadStuff(){
$timeout(function() {
vm.post = {
title: "Post Title",
content: "Post Content"
};
}, 1000);
}
loadStuff();
}
function changeContent(){
vm.post.content = "<div>new content </div>";
}
</script>
</head>
<body ng-controller="MainCtrl as main">
<p ng-hide="main.post">Loading...</p>
<h3>{{main.post.title}}</h3>
<p>{{main.post.content}}</p>
<button onclick="changeContent();">change</button>
</body>
</html>
New bodyController()
function bodyController($scope, $injector) {
_bodyController = this;
$scope.title = "ttt";
$scope.content = "aaa";
$scope.comp = function(){
angular.element(document).injector().invoke(function ($compile) {
$compile(document.body)($scope);
});
}
myAPP.Run(function(){
$scope.title = globalOBJ.title;
$scope.content = globalOBJ.content;
$scope.comp();
});
}
You should change your '' to this:
<body ng-controller="MainCtrl" ng-model="demo" ng-change="comp();">
If you check the url from the first line of the error log: https://docs.angularjs.org/error/$compile/ctreq?p0=ngModel&p1=ngChange. The problem is explained:
Controller 'ngModel', required by directive 'ngChange', can't be
found! Description This error occurs when HTML compiler tries to
process a directive that specifies the require option in a directive
definition, but the required directive controller is not present on
the current DOM element (or its ancestor element, if ^ was specified).
To resolve this error ensure that there is no typo in the required
controller name and that the required directive controller is present
on the current element.
The directive 'ng-change' require a 'ng-model' to work properly, that is why you are getting an compile error.
Now your second question, "Why onclick doesn't work ?". You should never manipulate the DOM from the controller, if you have to do that use a directive. When you call "scopecomp()" from the ng-click that method is invoked from "within" the angular engine, it will fire an digest cycle which will process the "html" (it's more than that, I'm trying to keep it simple) and print what you expect, but when you add "{{demo}}" directly to the DOM, that variable will not be processed.
There is no need to change the DOM manually to do what you are looking for, check the snippet below. I simulated your "database request" with a timeout function.
angular.module("app", [])
.controller("MainController", MainController);
MainController.$injector = ['$timeout'];
function MainController($timeout) {
var vm = this;
vm.post = null;
function loadStuff() {
$timeout(function() {
vm.post = {
title: "Post Title",
content: "Post Content"
};
}, 1000);
}
loadStuff();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as main">
<p ng-hide="main.post">Loading...</p>
<h3>{{main.post.title}}</h3>
<p>{{main.post.content}}</p>
</div>
$FirebaseJS.Run(function(){
$scope.$apply(function(){
$scope.obj = globalOBJ;
});
});
Finally I got it.

Ways to declare Function in AngularJS Controller (controllerAs approach)

I use controller as approach instead of $scope. I have some problems with method calling from HTML. So, the question is that, how many ways exist in declare and call functions in this approach.
first: (If I want to do s.th. at first)
var vm= this ;
vm.dataOne=[];
function funcOne() {
myService.serviceFunc()
.then(function (response) {
vm.dataOne= response.data;
});
};
function activate() {
funcOne();
}
activate();
second: (If I want to initialize a variable based on a function returned value )
vm.dataTwo = function () {
doSomeThing();
}
Is there any way, too?
How should define a function in controller
which will be called from HTML, as
ng-click = "ctrl.dataTwo()";
Functions the way you've defined are private:
function functionOne() {
}; // Just function body, no need of semicolon
These are known as function declarations. Currently, they are only accessible within your controller.
To be able to call them, attach them to the controller so they become controller variables:
vm.functionOne = functionOne;
An advantage of this approach is that you can define functions after actually calling them, as opposed to how you do with $scope or $this. They are recognized via hoisting, and called.
About your initializing a returned value from a function, just call it:
vm.someVariable = someFunction();
Some references:
var functionName = function() {} vs function functionName() {}
Private Members in JavaScript
Angular Function Declarations, Function Expressions, and Readable Code
Angular Style Guide
First way using ng-controller="cntrl as vm" syntax:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
</div>
</body>
</html>
Second way using controllerAs as one of the attribute of directive:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.directive('customDir', function() {
return {
restrict: 'EA',
template: '<div>{{vm.name}}</div>',
controller: function(){
var vm = this;
vm.name = 'Custom Directive';
},
controllerAs: 'vm'
}
});
</script>
<body>
<div ng-app="MyApp">
<div custom-dir></div>
</div>
</body>
</html>
Way to calling a function with "controller as" syntax which is defined in controller but called in html:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
vm.someFunction = function() {
vm.name = 'Button is Clicked!!!';
};
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
<input type='button' ng-click="vm.someFunction()" value="Click" />
</div>
</body>
</html>
Other way, use function as constructor and add functionality to prototype
function Ctrl($window) {
this.$window = $window;
}
Ctrl.inject = ['$window']
Ctrl.prototype.click = function() {
this.$window.alert('clicked')
}
angular.module('app', [])
.controller('ctrl', Ctrl)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl as c'>
<button ng-click='c.click()'>Click me!</button>
</div>

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.

Refresh JSON Data Using Angular

Just finished a Codeacademy tutorial using angular to loop through some JSON data from a URL and display the data.
Would love to know how to implement it so the data would be updated if the JSON data was changing periodically!
I know I need to maybe refresh the http get request,but after that I'm not sure.
If someone could point me in the right direction I would really appreciate it!
Thanks!
services/forecast.js
app.factory('forecast', ['$http', function($http) {
return $http.get('http://json-time.appspot.com/time.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
controllers/MinorController.js
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
test.html (view)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular -->
<script src="js/shared/angular.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="js/shared/bootstrap.min.js"></script>
</head>
<body ng-app="myApp">
<div class="container" ng-controller="MinorController">
<div class="row">
<h1>Time JSON Example</h1>
<h2>{{ fiveDay.tz }} </h2>
<h2> {{ fiveDay.hour }} </h2>
<h2> {{ fiveDay.datetime }} </h2>
<h2> {{fiveDay.second }} </h2>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<script src="js/controllers/MinorController.js"></script>
<!-- Services -->
<script src="js/services/forecast.js"></script>
</body>
</html>
You can do it by using setInterval like so.
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
Now your service will call every 5 seconds and rebind your object.
If you go to another screen, then the routeChangeStart event will call for the interval to be cleared.
You can do it on several ways:
You can make http request in loop every few seconds
setInterval(function(){ alert("Hello"); }, 3000);
If you develop server data source you can setup real time connection, using i.e. SignalR or Socket

Categories

Resources