AngularJS dynamic urls - javascript

For example I have 3 links on my page:
A
B
C,
When I click A it should function something like this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("some.url/A")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
"A" should dynamically reach the url when I click A. How to do it angularJs

try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myFunc = function(url) {
console.log(url);
$http.get("some.url/"+url)
.then(function(response) {
$scope.myWelcome = response.data;
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="myFunc('A')">A</button>
<button ng-click="myFunc('B')">B</button>
<button ng-click="myFunc('C')">C</button>
</div>
</body>

Related

Call one function in both controller - AngularJS 1.x

I have two controllers
user.controller.js:
const fetchApi = () => {
console.log('fetching');
};
fetchApi();
I want to call this function in my dashboard.controller.js without writing this same hard code in dashboard controller again.
var app = angular.module('myapp', []);
var fetchApi = function($scope){
console.log("fetching");
};
fetchApi.$inject = ['$scope'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="dashboardCtrl"></div>
<div ng-controller="homeCtrl"></div>
</div>
EDIT : inject service
var app = angular.module('myapp', []);
var fetchApi = function($scope, RestService){
console.log("fetching");
RestService.getUser();
};
fetchApi.$inject = ['$scope', 'RestService'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);
app.service('RestService', ['$http',
function($http){
this.getUser = function() {
//$http api call
console.log("get user");
}
}
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="dashboardCtrl"></div>
<div ng-controller="homeCtrl"></div>
</div>

Not getting json data from json-angularjs call to an external url with $http.get

controller code:
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
$http.get('data.json').then(function(data) {
$scope.artist = data;
});
});
html code:
<div class="main" ng-controller="myController">
<ul class="artistlist">
<li class="artist cf" ng-repeat="x in artist">
<img ng-src="images/{{x.shortname}}_tn.jpg" alt="Photo of {{x.name}}">
<div class="info">
<h2>{{x.name}}</h2>
<h3>{{x.reknown}}</h3>
</div>
</li>
</ul>
</div>
Try this: Your Controller
var myApp = angular.module('myApp', [])
myApp.controller("myController", ["$scope", "$http", function ($scope, $http) {
$http.get("data.json").then(
function (response) { $scope.artist = response.data },
function (error) { console.log(error) }
)
}])
Make sure you check the browser's console
The $http service has data property that is used to fetch the details.
data – {string|Object} – The response body transformed with the transform functions
Change your controller code like this
var myApp=angular.module('myApp',[]);
myApp.controller('myController', function($scope,$http){
$http.get('data.json').then( function(response){
$scope.artist = response.data;
});
});
And initialise your html with ng-app="myApp"

How can I share JSON data with one scope?

This is my Angular controller:
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
var promise = $http.get("url1")
.then(function (response) {
console.log(response);
$scope.files = [response.data]
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
$scope.files = response2.data;
return response2.data;
})
}])
my HTML
<div ng-app="app" ng-controller="ctrl">
<script type="text/ng-template" id="category">
<strong>{{file.Name}}</strong>
<ul ng-if="(files | filter:{ParentId : file.Id}).length > 0">
<li ng-repeat="file in files | filter: {ParentId : file.Id" ng-include="'category'"></li>
</ul>
</script>
<ul class="btn-highlight plus">
<li ng-repeat="file in files | filter: {ParentId : 0}" ng-include="'category'"></li>
</ul>
</div>
ParentId = response.data.Id in my Angular controller.
My question is how can I include response and response2 in my scope called $scope.files at the same time and call my response.data.Id in my html code(ParentId)?
You should change your code to this.
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
var promise = $http.get("url1")
.then(function (response) {
var response1 = [];
console.log(response);
response1 = response.data;
$scope.files = [response.data]
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
var response2 = [];
response2 = response2.data;
var allResponse = [];
allResponse = response2.data.concat(response1);
$scope.files = allResponse;
return response2.data;
})}])
Try setting the scope outside of the promise .. but anyway why in god's name are you using nested promises instead of the $q service ? That's callbacksHell , and it sucks as code ..
Use the $q , that's its basic use case ..
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
$scope.files = [];
var promise = $http.get("url1")
.then(function (response) {
console.log(response);
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
$scope.files = response2.data;
return response2.data;
})
}])

How to write HTML code inside of DIV after send POST request in AngularJs

I want to write HTML code inside of DIV after getting data from service but it doesn't work. These are my html and js codes. How can I fix?
Thanks.
index.html:
<html>
<head>
<title>AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-sanitize.js"></script>
<script src=script></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div ng-bind-html="htmlcode">
</div>
</div>
</body>
</html>
script.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
});
}]);
})(window.angular);
script1.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
});
}]);
})(window.angular);
RESULT (script1.js):
Item 1
Item 2
SubItem-1 is not shown as a sub item of Item-1
RESULT (script.js):
Item 1
SubItem-1
Item 2
Do not manipulate html inside the controller use diectives or services for that. This should be done with an ng-repeat instead.
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
$scope.items = [];
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
$scope.items.concat(result.items);
});
}]);
})(window.angular);
// template
<body ng-app="myApp">
<div ng-controller="myController">
<ul class="items">
<li ng-repeat="item in items">
{{item.name}}
<ul class="sub-items">
<li ng-repeat="subitem in item.subItems">{{subitem.name}}</li>
</ul>
</li>
</ul>
</div>
</body>
// items.json
{
"items": [
{
"name": "item1",
"subItems": [
"name": "subItem1"
]
}
]
}

Loading JSON Data via NG click (JS)

I am having a problem loading a set of JSON data with NG CLICK. Without the clickButton function the data loads fine. Is my JSON data structured properly? Here is my fiddle. Click [here] (http://jsfiddle.net/al321/08rjqv4k/3/ "mouse over")
$scope.items = [
{
"Name":"Sam",
"Address":"Street",
"Phone":"111",
"status":"Available"
},
{
"Name":"Tom",
"Address":"Road",
"Phone":"222",
"status":"Busy"
},]
--js
var app = angular.module('myApp', []);
app.controller('myController',
['$scope', '$http', function($scope, $http) {
$scope.clickButton = function() {
$http.get('data.json').success(function(data) {
$scope.items = data.items;
});
}
}]);
Plunker
JS
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.clickButton = function() {
$http.get('data.json').success(function(data) {
$scope.items = data;
});
}
}]);
Markup
<body ng-controller="myController">
<div ng-app="myApp">
<div ng-controller="myController">
<button ng-click='clickButton()'>Load Data</button>
<ul ng-repeat="item in items">
<li ng-repeat="(key, val) in item">{{key}}: {{val}}
</li>
</ul>
</div>
</div>
</body>
JSON
[
{
"Name":"Sam",
"Address":"Street",
"Phone":"111",
"status":"Available"
},
{
"Name":"Tom",
"Address":"Road",
"Phone":"222",
"status":"Busy"
}
]
Is this what you are trying to accomplish?
Just replace the contents of the clickButton() function with your ajax calls.
You forgot to put the () on ng-click="clickButton(). You need to actually call the function.
Plunker
To add the search functionality you mentioned in the comment, just add a filter to the first ng-repeat:
ng-repeat="item in items| filter: {Name: search}"
Plunker with search

Categories