Here is my html code:
<div ng-app="myApp" ng-controller="customersCtrl">
<p id="druzyny"></p>
</div>
and then in angular script:
var app = angular.module('myApp', []);
document.getElementById("search1").onclick = app.controller('customersCtrl', function($scope, $http){
var place = document.getElementById("place").value;
var sel1 = document.getElementById("sel1").value;
var sel2 = document.getElementById("sel2").value;
var req = {
method: 'post',
url: 'findTournament',
headers: {
'Content-type': 'application/json'
},
data: {place: 'test'}
};
$http(req).then(function(response){
});
});
I`ve got button id="search1" and i want that angular execute only when i click this button, no automatically when page is reload, is it possible?
Thanks for answears
HTML:
<div ng-app="myApp" ng-controller="customersCtrl as customers">
<input data-ng-model="customers.place">
<input data-ng-model="customers.sel1">
<input data-ng-model="customers.sel2">
<button data-ng-click="customers.init()"></button>
</div>
JS:
angular.module('myApp', []);
angular
.module('myApp')
.controller('customersCtrl', function($scope, customersService){
var vm = this;
vm.init = function(){
customersService.findTournament({place: vm.place, sel1: vm.sel1, sel2: vm.sel2})
.then(function(res){});
};
});
angular
.module('myApp')
.service('customersService', function($http){
return {
findTournament: findTournament
};
function findTournament(data){
return $http.post('findTournament', data);
}
});
Related
I have setup an RXJS observable. I have two components which subscribe to a subject in service factory. How do I unsubscribe a selected component to the subject so that a button is pressed it stops listening to the subject broadcast?
See my jsfiddle Unsubscribe App
My code:
<div ng-app="myApp" ng-controller="mainCtrl">
<script type="text/ng-template" id="/boxa">
BoxA - Message Listener: </br>
<strong>{{boxA.msg}}</strong></br>
<md-button ng-click='boxA.unsubcribe()' class='md-warn'>Unsubscribe A</md-button>
</script>
<script type="text/ng-template" id="/boxb">
BoxB - Message Listener: </br>
<strong>{{boxB.msg}}</strong></br>
<md-button ng-click='boxB.unsubcribe()' class='md-warn'>Unsubscribe B</md-button>
</script>
<md-content class='md-padding'>
<h3>
{{name}}
</h3>
<label>Enter Text To Broadcast</label>
<input ng-model='msg'/></br>
<md-button class='md-primary' ng-click='broadcastFn()'>Broadcast</md-button></br>
<h4>
Components
</h4>
<box-a></box-a></br>
<box-b></box-b>
</md-content>
</div><!--end app-->
var app = angular.module('myApp', ['ngMaterial']);
app.controller('mainCtrl', function($scope,msgService) {
$scope.name = "Observer App Example";
$scope.msg = 'Message';
$scope.broadcastFn = function(){
msgService.broadcast($scope.msg);
}
});
app.component("boxA", {
bindings: {},
controller: function(msgService) {
var boxA = this;
boxA.msgService = msgService;
boxA.msg = '';
boxA.msgService.subscribe(function(obj) {
console.log('Listerner A');
boxA.msg = obj;
});
boxA.unsubscribe=function(){
};
},
controllerAs: 'boxA',
templateUrl: "/boxa"
})
app.component("boxB", {
bindings: {},
controller: function(msgService) {
var boxB = this;
boxB.msgService = msgService;
boxB.msg = '';
boxB.msgService.subscribe(function(obj) {
console.log('Listerner B');
boxB.msg = obj;
});
boxB.unsubscribe=function(){
};
},
controllerAs: 'boxB',
templateUrl: "/boxb"
})
app.factory('msgService', ['$http', function($http){
var msgSubject = new Rx.ReplaySubject();
return{
subscribe:function(subscription){
msgSubject.subscribe(subscription);
},
broadcast:function(msg){
console.log('success');
msgSubject.onNext(msg);
}
}
}])
As per my comment above the new RxJs 5 Beta now changed from subscription.dispose() to subscription.unsubscribe() Please refer to here https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#subscription-dispose-is-now-unsubscribe
Please see updated fiddle: here
the subscribe function returns a Disposable to work with and you must first return the subscription from your factory (line 60):
subscribe: function(subscription){
return msgSubject.subscribe(subscription);
}
This will let you store your subscription in each controller to work with in the future. (line 21 & 42)
var boxASubscription = boxA.msgService.subscribe(function(obj) {
console.log('Listerner A');
boxA.msg = obj;
});
You can then call the dispose method on the subscription when you want to unsubscribe:
boxA.unsubscribe = function(){
console.log('Unsubscribe A');
boxASubscription.dispose();
};
n.b.
For some reason I couldn't get your demo to work with <md-button> so I changed this to <button> for the sake of the demo.
I am using AngularJs to retrieve the data from ASP.Net Controller.
The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
$scope.lookupItems = response;
console.log($scope.lookupItems);
},
function (error) { alert("error"); });
// console.log($scope.listItems);
});
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
The Json Retrieved from the server:
[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]
The most likely issue (assuming that your app and controller are constructed and referenced properly) is that the object returned from the promise contains a .data property which actually holds your JSON data.
Try this:
$http({ method: 'GET', url: '/home/listvalues?listid=3' })
.then(function (response) {
$scope.lookupItems = response.data;
console.log($scope.lookupItems);
},
function (error) {
alert("error");
});
I think you just forgot to wrap your app with ng-app:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$scope.lookupItems = [{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}];
console.log($scope.lookupItems);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Appp">
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
</body>
You probably misspelled Appp. Make sure your module definition in your javascript:
var app = angular.module('App', []); //Changed to App from Appp
matches your app declaration in your html
<div ng-app="App">
...controller declaration...
...body.....
</div>
I'm somewhat new to the JS world, so I'm struggling a bit as to what I did wrong. My sample data from wordpress API is not working. Any ideas what I did wrong:
app.controller('FeedCtrl', function($http, $scope, $ionicLoading) {
console.log("Loading FeedCtrl");
$scope.stories = [];
function loadStories(params, callback) {
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/', {params: params})
.success(function(response) {
var stories = [];
angular.forEach(response.data.children, function(child) {
stories.push(child.data);
});
callback(stories);
});
}
$scope.loadOlderStories = function() {
var params = {};
if ($scope.stories.length > 0) {
params['after'] = $scope.stories[$scope.stories.length - 1].name;
}
loadStories(params, function(olderStories) {
$scope.stories = $scope.stories.concat(olderStories);
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};
$scope.loadNewerStories = function() {
var params = {'before': $scope.stories[0].name};
loadStories(params, function(newerStories) {
$scope.stories = newerStories.concat($scope.stories);
$scope.$broadcast('scroll.refreshComplete');
});
};
I've made a simplified example with your data.
Click the 'Load more' button to retrieve some posts. You should see a list with the title and the author of a post.
EDIT: There appears to be some cross-domain request issues, that's why the 'Load stories' button won't work. Just try to reflect this code inside your controller, it should work.
var app = angular.module('myApp', []);
app.controller('feedCtrl', function ($scope, $http) {
$scope.stories = [];
$scope.loadStories = function loadStories() {
console.log('loading stories');
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/')
.then(function onSuccess(response) {
console.log(response);
$scope.stories = response.data.posts;
}, function onFailed(error) {
console.error('Error:', error)
});
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="feedCtrl">
<button data-ng-click="loadStories()">Load stories</button>
<ul>
<li data-ng-repeat="story in stories">Title: {{ story.title }} - {{ story.author.first_name }} {{ story.author.last_name }}</li>
</ul>
</div>
</body>
</html>
Normally we wouldn't handle $http calls in our angular.controller. This needs to be done in an angular.service.
I have got a problem displaying content from jsonp request:
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'domain/api/getposts/?auth_key=s2mEus39R296M5F6n343A3dh9c62f7cm&custom_post=updates&callback=JSON_CALLBACK';
$scope.content = [];
$scope.fetchContent = function() {
console.log($scope.url);
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
};
$scope.fetchContent();
}
and my html template is:
<div id="container" ng-controller="ContentCtrl">
<content-item ng-repeat="item in content" content="item">{{item.ID}}
</content-item>
</div>
Am I doing anything wrong? Really apprecite your help...
So I keep getting this ReferenceError: $http is not defined, even though I have included $http in the controller, which seems to be the most common cause of this error message. I've tried also passing $http into the function itself, but that doesn't solve it.
I feel like I am missing something SUPER obvious, so any help would be much appreciated, thank you!
I've included the entire script, just for clarity's sake. You can see the post request towards the end of the script, inside the finaliseDay function.
Thanks!
Here is the error:
ReferenceError: $http is not defined
at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c
Here is the HTML first
<!doctype html>
<html ng-app="goalzy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="goalzy.js"></script>
</head>
<body>
<div class="container">
<div class="well">
<h2>Goalzy</h2>
Dev TODO
<ul>
<li>Hook up the API to persist data</li>
</ul>
<div ng-controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining today</span>
<span>You're at {{percentComplete()}}% completion</span>
[ finalise day ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<hr>
<div class="historial" ng-repeat="h in historicalDailyPercentages">
<ul>
<li>Date: {{h.date}}</li>
<li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
<li><div>Tweet it!</div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
And here is the JS:
//Goalzy.js
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];
$scope.historicalDailyPercentages = [];
$scope.addTodo = function() {
if ($scope.todoText != "") {
if ($scope.todos.length < 3) {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
//Save to DB
}
else {
alert("You can only have 3 todos per day!");
$scope.todoText = '';
}
} else {
alert("you must write something");
}
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.percentComplete = function() {
var countCompleted = 0;
angular.forEach($scope.todos, function(todo) {
countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
console.log(countCompleted);
});
var totalCount = $scope.todos.length;
var percentComplete = countCompleted / totalCount * 100;
return percentComplete;
}
$scope.finaliseDay = function(percentComplete) {
alert("You're finalising this day with a percentage of: " + percentComplete);
var today = new Date();
var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) {
return item.date.getFullYear() === today.getFullYear() &&
item.date.getMonth() === today.getMonth() &&
item.date.getDate() === today.getDate();
});
//Confirm that nothing has alreayd been posted for today
if (!alreadyPresent) {
$scope.historicalDailyPercentages.push({
percent: percentComplete,
date: today
});
// Simple POST request example (passing data) :
$http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("data" + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("data" + data);
});
}
else {
alert("You're all set for today - see you tomorrow!");
}
console.log($scope.historicalDailyPercentages);
}
}]);
Provider won't be available inside controller with suffix 'Provider', you can do access them by provider name only here it would be $http only, also remove ;
after config initialization
$httpProvider setting should be done inside the angular config phase
CODE
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
.controller('TodoController', ['$scope', '$http', function($scope, $http) {
//controller code here
}]);
Note: For sure you should remove $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'; line from controller
Working Plunkr
You don't have to use "$httpProvider" in controller, use $http instead.
e.g.
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
As best practice, do not configure provider ($http) in controller. Do it in config section. as below
var app = angular.module('goalzy', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
app.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.title="scope title";
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);
see working plunk at http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/ with your html.