Fill angularjs scope with a dynamic array - javascript

My Angular App works with
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
$scope.urls = [
{
"url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=KhzGSHNhnbI")
},
{
"url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=OPxeCiy0RdY")
}
]
});
</script>
But it doesn't work with
<script>
urls = [
{
"url":"https://www.youtube.com/watch?v=KhzGSHNhnbI"
},
{
"url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"
}
]
</script>
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope = [];
urls.forEach(function (url, i) {
$scope.push(new myUrl($sce.trustAsResourceUrl(url)));
});
});
</script>
Update: still doesn't work
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope.urls = [];
urls.forEach(function (url, i) {
$scope.urls.push(new myUrl($sce.trustAsResourceUrl(url)));
});
});
</script>
Error: [$sce:itype] http://errors.angularjs.org/1.4.3/$sce/itype?p0=resourceUrl

replace $scope.push(new myUrl($sce.trustAsResourceUrl(url))); with
$scope.push(new myUrl($sce.trustAsResourceUrl(url.url)));
https://plnkr.co/edit/tpl:FrTqqTNoY8BEfHs9bB0f?p=preview
urls = [
{
"url":"https://www.youtube.com/watch?v=KhzGSHNhnbI"
},
{
"url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"
}
]
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope.urls = [];
urls.forEach(function (url, i) {
$scope.urls.push(new myUrl($sce.trustAsResourceUrl(url.url)));
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p ng-repeat="url in urls">Hello {{url.url}}!</p>
</body>
</html>

Related

Where To Put AngularJS Directive-Template Functions

If I do something like this in my directive:
template: '<button ng-click="Done()">DONE</button>'
Then where do I put my $scope.Done() function? I have it in a controller here but that doesn't seem to work
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="myApp" ng-controller="myctrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div mydiv></div>
<script>
angular.module("myApp", [])
.controller("myctrl", function($scope) {
$scope.Done = function() {
alert('Done');
};
});
angular.module("myApp", [])
.directive("mydiv", function() {
return {
template: '<button ng-click="Done()">DONE</button>'
};
});
</script>
</body>
</html>
Doing something like this will serve your purpose. Give a try ..
angular.module("myApp", [])
.directive("mydiv", function() {
return {
template: '<button ng-click="Done()">DONE</button>',
link: function (scope, element, attrs) {
scope.Done = function () {
alert('Done');
}
}
};
});
Remove below fuction from controller.
$scope.Done = function() {
alert('Done');
};
Not good approach to set the function directly, you need to bind it.
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="myApp" ng-controller="myctrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div mydiv on-done="Done()"></div>
<script>
angular.module("myApp", [])
.controller("myctrl", function($scope) {
$scope.Done = function() {
alert('Done');
};
});
angular.module("myApp", [])
.directive("mydiv", function() {
return {
scope: {
onDone: '&'
},
template: '<button ng-click="onDone()">DONE</button>'
};
});
</script>
</body>
</html>
Here's a working example:
http://jsfiddle.net/ADukg/17585/

angularjs Failed to instantiate module ui.bootstrap.demo

I am learning angularjs and i am stuck at one point. I keep getting error
ncaught Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap.demo due to:
Error: [$injector:nomod] Module 'ui.bootstrap.demo' is not available!
Below is my html file
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
<script src="resources/js/main.js"/>
<script src="resources/js/gsenv.js"/>
<script src="resources/js/CarouselController.js"/>
</head>
However if i dont write the javascripts in separate file it works as exected
<script type="text/javascript">
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope, $http, dataShare) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.sendEnvName = function(data) {
dataShare.sendEnvNameDetails(data);
}
$scope.addSlide = function (envName) {
slides.push({
text: envName,
id: currIndex++
});
};
$http.get("http://localhost:8080/getEnvList")
.success(function (data) {
for (var i in data) {
$scope.addSlide(data[i].envName);
}
});
});
It works fine this way, not able to understand what could be the issue
main.js
var app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap', 'ngTable']);
jsenv.js
app.factory('dataShare',function($rootScope){
var service = {};
service.envName = 'no-env'
service.sendEnvNameDetails = function(data){
console.log(data)
this.envName = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.envName;
};
return service;
});
carousel
app.controller('CarouselDemoCtrl', function ($scope, $http, dataShare) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.sendEnvName = function(data) {
dataShare.sendEnvNameDetails(data);
}
$scope.addSlide = function (envName) {
slides.push({
text: envName,
id: currIndex++
});
};
$http.get("http://localhost:8080/getEnvList")
.success(function (data) {
for (var i in data) {
$scope.addSlide(data[i].envName);
}
});
});
Change your controllers and factories:
From:
app.controller('CarouselDemoCtrl', function ($scope, $http, dataShare) { });
To:
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope, $http, dataShare) { });
From:
app.factory('dataShare',function($rootScope){});
To:
angular.module.factory('dataShare',function($rootScope){});

Unknown provider error - AngularJS App issue

var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cart.php',
controller: 'ctrl',
resolve: {
            categories: function(cartService){
console.log('inside resolve categories')
                return cartService.getCategories();
            }
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrl', function (categories, $scope) {
$scope.items = categories;
});
myApp.service("cartService", function ($http, $q) {
this.getCategories = function () {
var deferred = $q.defer();
$http.get('js/categories.js')
.then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
});
myApp.run(['$rootScope',function($rootScope){
$rootScope.stateIsLoading = false;
$rootScope.$on('$routeChangeStart', function(e, current, pre) {
$rootScope.stateIsLoading = true;
var fullRoute = current.$$route.originalPath;
if(fullRoute == '/')
{
console.log('load categoreis and products')
}
});
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.stateIsLoading = false;
console.log('route changed');
});
$rootScope.$on('$routeChangeError', function() {
//catch error
});
}]);
I have placed the ng-app and ng-controller directives at the top of the HTML
<html lang="en" ng-app="MyApp" ng-controller="ctrl">
But when I run the HTML I get the following error
Error: [$injector:unpr] Unknown provider: categoriesProvider <-
categories <- ctrl
How can I fix this ?
Edit: If I remove ng-controller="ctrl" from the HTML, then no errors
You got that error just because, you are using the same controller for both index.php and 'partials/cart.php'
Create a separate controller for 'partials/cart.php' to resolve this
problem
Code Snippet:
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('indexCtrl', function($scope) {
$scope.title = 'Header';
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
controller: 'categoryCtrl',
resolve: {
categories: function(cartService){
return cartService.getCategories();
}
}
});
});
app.controller('categoryCtrl', function (categories, $scope) {
$scope.items = categories;
});
app.service("cartService", function() {
this.getCategories = function() {
return ['A', 'B', 'C'];
};
});
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script data-require="angular-route#1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="indexCtrl">
<h1>{{title}}</h1>
<div ng-view></div>
</body>
</html>
you have to define the categories service/factory which is injected in your controller 'ctrl'.

AngularJS - How can I get data from GET method

My Controller:
angular.module('apartmentCtrl', [])
.controller('ApartmentController', function ($scope, $http, Apartment) {
$scope.loading = true;
$scope.myLocation = '';
Apartment.get($scope.myLocation).success(function (data) {
$scope.apartments = data;
$scope.loading = false;
});
});
My Service
angular.module('apartmentService', [])
.factory('Apartment', function ($http) {
return {
get: function (myLocation) {
//return $http.get('/api/apartments');
return $http({
method: 'GET',
url: '/api/apartments',
//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: {location: myLocation}
});
}
};
});
My HTML:
<input type="text" name="myLocation" class="form-control" ng-model="myLocation">
How can I get data from GET method by AngularJS and pass it to params
If you want to pass some value from your form as "location", you should bind it to your model, and explicitly pass it to your factory get function.
I have a working example here, it just does a window alert showing you the typed in data, in place of the $http call, but the idea is the same.
http://plnkr.co/edit/fRra6RfQrSZb8rzrm4XF?p=preview
Html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<form ng-submit="getIt()">
<input type="text" ng-model="myLocation"/>
<input type="submit"/>
</form>
</body>
</html>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Apartment) {
$scope.name = 'World';
$scope.myLocation = 'Hollywood';
$scope.getIt = function() {
Apartment.get($scope.myLocation);
}
});
app.factory('Apartment', function ($window) {
return {
get: function (whatLocation) {
$window.alert(whatLocation);
}
};
});

Request REST service

I am currently at beginner level at javascript and angular.js framework.
My problem is that I cannot make ngResource working .
Plunker
My code:
JS:
var geolocationControllers = angular.module('geolocationControllers', ['ngResource']);
geolocationControllers.controller('geolocationControllers', ['$scope', '$resource',
function($scope, $resource) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = $resource('http://nominatim.openstreetmap.org/reverse?format=json', {}, {
query: {
method: 'GET',
params: {
lat: position.coords.latitude,
lon: position.coords.longitude
}
}
});
console.log($scope.position);
});
});
}
}
]);
HTML:
<div class="container" ng-controller="geolocationControllers">
<label for="location">Your location:</label>
<input type="text" id="location" size="120" ng-model="position"/>
</div>
This outputs to console and is also in input element:
function Resource(value) { shallowClearAndCopy(value || {}, this); }
You can do something like this... This will work, I tested it in my browser... you will have to rename the parts you need to...
HTML
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>untitled</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="myController">
<label for="location">Your location:</label><br>
<input type="text" id="location" size="120" ng-model="positionText"/>
</body>
</html>
And Javascript
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope, $http) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (curPosition) {
var curLongi = curPosition.coords.longitude;
var curLati = curPosition.coords.latitude;
$http.get('http://nominatim.openstreetmap.org/reverse?format=json&lat='+curLati.toString()+'&lon='+curLongi.toString()).success(function (data) {
alert(JSON.stringify(data));
$scope.positionText = data.display_name;
});
});
}
});

Categories

Resources