How to call controller function from other controller angularjs - angularjs

please look at this code. My button must call function checkResults() from controller CtrlTwo.
How to do this?
var myApp = angular.module('myApp', []);
function CtrlOne($scope){
$scope.greet = 'Hi! ';
}
function CtrlTwo($scope){
$scope.$emit('checkResults', function(){
alert('Function is called!');
}
);
}
<body ng-app="myApp">
<div ng-controller="CtrlOne">
{{greet}}
<input type="submit" class="btn btn-primary pull-right" value="Check results" ng-href='#here' ng-click='checkResults()'/>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</body>

Here, hopefully this example will help you:
Javascript:
var myApp = angular.module('myApp', []);
myApp.controller('CtrlOne', function($scope){
$scope.greet = "hi!"
var nTimes = 0;
$scope.$on('myEvent', function(){
$scope.greet = "Hi! The event has been called " + (++nTimes) + " times";
});
});
myApp.controller('CtrlTwo', function($scope){
$scope.emitCustomEvent = function(){ $scope.$emit('myEvent'); };
});
View:
<div ng-app="myApp">
<div ng-controller="CtrlOne">
{{greet}}
<div ng-controller="CtrlTwo">
<input type="button" value="Check results" ng-click="emitCustomEvent()" >
</div>
</div>
</div>
Working Example

Related

How to make uib-datepicker's show-spinners to be dynamically updated?

As you can see in that snippet, I've set the attributes show-meridian and show-spinners to match to the variable $scope.myBool.
I've added as well a green button that says change! and toggles $scope.myBool.
While show-meridian is perfectly reacting to any change in $scope.myBool, show-meridian is not being updated.
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.9/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.3.0/ui-bootstrap-tpls.min.js"></script>
<script>
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TimepickerDemoCtrl', function($scope, $log) {
$scope.mytime = new Date();
$scope.hstep = 1;
$scope.mstep = 15;
$scope.options = {
hstep: [1, 2, 3],
mstep: [1, 5, 10, 15, 25, 30]
};
$scope.ismeridian = true;
$scope.toggleMode = function() {
$scope.ismeridian = !$scope.ismeridian;
};
$scope.update = function() {
var d = new Date();
d.setHours(14);
d.setMinutes(0);
$scope.mytime = d;
};
$scope.changed = function() {
$log.log('Time changed to: ' + $scope.mytime);
};
$scope.clear = function() {
$scope.mytime = null;
};
$scope.myBool = false;
});
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
.timepickercontainer .uib-timepicker .btn-link {
display: none;
}
</style>
</head>
<body>
<div ng-controller="TimepickerDemoCtrl">
<div class="timepickercontainer">
<div uib-timepicker ng-model="mytime" ng-change="changed()" arrowkeys="false" hour-step="hstep" minute-step="mstep" show-meridian="myBool"
show-spinners="!myBool" ></div>
</div>
<pre class="alert alert-info">Time is: {{mytime | date:'shortTime' }}</pre>
<div class="row">
<div class="col-xs-6">
Hours step is:
<select class="form-control" ng-model="hstep" ng-options="opt for opt in options.hstep"></select>
</div>
<div class="col-xs-6">
Minutes step is:
<select class="form-control" ng-model="mstep" ng-options="opt for opt in options.mstep"></select>
</div>
</div>
<hr>
<button type="button" class="btn btn-info" ng-click="toggleMode()">12H / 24H</button>
<button type="button" class="btn btn-default" ng-click="update()">Set to 14:00</button>
<button type="button" class="btn btn-danger" ng-click="clear()">Clear</button>
<button class='btn btn-success' ng-click='myBool = !myBool'>change!</button>
</div>
</body>
</html>
This is a hacky soluction. how i say in the comment is better to maka a issue in the repo of the directive.
for make spinner hide and show you must enter in the ui-bootstrap-tpls.js file and find this line
$scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
$scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;
and substitute with this
$scope.showSpinners = timepickerConfig.showSpinners;
if ($attrs.showSpinners) {
watchers.push($scope.$parent.$watch($parse($attrs.showSpinners),
function(value) {
$scope.showSpinners = !!value;
updateTemplate();
}));
}
heres is my plnkr
example

angular js The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part

enter image description here
The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part. I did not get it. My English is not very good.
html
<div ng-repeat="choice in choices">
<input type="text" -ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
css
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
Try this one
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myapp" ng-controller="control">
<div ng-repeat="choice in choices">
<input type="text" ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
</div>
<script>
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>
</body>
</html>

How to modify service url paramer in angularjs

I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!
HTML:
<section ng-controller="MainController">
<form action="" class="form-inline well well-sm clearfix" >
<span class="glyphicon glyphicon-search"></span>
<input type="text" placeholder="Search..." class="form-control" ng-model="city" />
<button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button>
</form>
<h1>{{fiveDay.city.name}}</h1>
<div ng-repeat="day in fiveDay.list" class="forecast">
<div class="day">
<div class="weekday">
<p>{{ day.dt*1000 | date}}</p>
<!-- <p>{{ parseJsonDate(day.dt)}}</p> -->
</div>
<div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div>
<div class="temp">{{day.weather[0].description}}</div>
<div class="temp">Max {{ day.main.temp_max }}°</div>
<div class="temp">Min {{ day.main.temp_min }}°</div>
</div>
</div>
</section>
JS:
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
forecast.city="orlando";
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
City is a variable part in your forecast factory so need to pass it as an argument in function will be the recommended for you
Try this
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
var city = "orlando";
forecast.getWeatner(city).success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var key = "a1f2d85f6babd3bf7afd83350bc5f2a6";
return {
getWeatner: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5');
}
}
}]);
增加参数 callback , 回调:JSON_CALLBACK
$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... });

AngularJS , pushing empty element

Im quite new with angular. What am i freaky about is that following code is showing empty buttons (edit/delete) even if it looks empty (on start) :
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form ng-submit="todoAdd(item)">
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="submit" value="Add New">
</form>
<br>
<div ng-repeat="x in todoList">
<span ng-bind="x.todoText"></span><button id="#edit" ng-click="edit(item)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [{}];
$scope.todoAdd = function(item) {
$scope.todoList.push({todoText:$scope.todoInput);
$scope.todoInput = "";
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
//function
};
});
</script>
</body>
</html>
And also can somebody to help me after clicking on edit to push todoText to input and change caption of addnew to save? and afterthen change it to addNew again?
Thank you very much
Replace line
$scope.todoList = [{}];
to
$scope.todoList = [];
Then, it wouldn't show you empty line.
//Full code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form>
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="button" value="{{actionName}}" ng-click="todoAdd()" />
</form>
<br>
<div ng-repeat="x in todoList">
<span>{{x.todoText}}</span><button id="#edit" ng-click="edit(x)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [];
$scope.actionName = 'Add';
$scope.todoAdd = function() {
if($scope.actionName === 'Add'){
$scope.todoList.push({todoText:$scope.todoInput});
$scope.todoInput = "";
} else {
var index = $scope.todoList.indexOf($scope.temp);
console.log('index: ' + index);
$scope.todoList.splice(index, 1, {todoText:$scope.todoInput});
$scope.actionName = 'Add';
}
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
$scope.todoInput=item.todoText;
$scope.temp = item;
$scope.actionName = 'Save';
};
});
</script>
</body>
</html>

How to show message for a certain time in angularjs

I'm displaying a message when the user clicks on the button.
I want to show this message for 10 seconds and then hide it.
My code is the following:
<script>
function Ctrl($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function() {
$scope.msg="hi";
};
}
</script>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting()">click</button>
{{msg}}
</div>
You can set a variable that determines whether to show the message or not and hide it and after 10,000 seconds. You will have to inject $timeout as shown below. Then in your view you will need to wrap {{msg}} in a span in order to use ng-show
<script>
function Ctrl($scope, $window, $timeout) {
$scope.greeting = 'Hello, World!';
$scope.showGreeting = false;
$scope.doGreeting = function() {
$scope.msg="hi";
$scope.showGreeting = true;
$timeout(function(){
$scope.showGreeting = false;
}, 10000);
};
}
</script>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting()">click</button>
<span ng-show="showGreeting ">{{msg}}</span>
</div>
The way I did to show a message for a certain time in angularjs was using AngularJS-Toaster library
To use the library follow this steps:
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js" ></script>
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.js"></script>
Add toaster container directive:
<toaster-container></toaster-container>
Prepare the call of toaster method:
// Display an info toast with no title
angular.module('main', ['toaster'])
.controller('myController', function($scope, toaster) {
$scope.pop = function(){
toaster.pop('success', "title", "text");
};
});
Call controller method on button click:
<div ng-controller="myController">
<button ng-click="pop()">Show a Toaster</button>
</div>
Here you can see a Plunker showing many kinds of toasts showing differents messages
Add the $timeout dependency to your controller. Here's a fiddle:
<div ng-app>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting()">click</button>
<div class="ng-hide" ng-show="showMessage">{{msg}} {{ greeting }}</div>
</div>
</div>
function Ctrl($scope, $window, $timeout) {
var messageTimer = false,
displayDuration = 5000; // milliseconds (5000 ==> 5 seconds)
$scope.showMessage = false;
$scope.msg = "hi";
$scope.doGreeting = function () {
if (messageTimer) {
$timeout.cancel(messageTimer);
}
$scope.showMessage = true;
messageTimer = $timeout(function () {
$scope.showMessage = false;
}, displayDuration);
};
}

Resources