binding selected item angularjs - angularjs

I can not use selectedItem1 in the controller for some calculation in the following code:
<div class="col-md-3">
<label>Vendere:</label>
<select ng-model="selectedItem1" ng-options="(rosa.nome+' '+rosa.costo) for rosa in rose"></select>
</div>
with the following controller:
var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $http){
$scope.budget0=60;
$scope.budget1=$scope.budget0 - $scope.selectedItem1.someprop;
}
I can understand why? Where i'm wrong?

I guess you need to give initial value to selectedItem1 Check out following example will help you:--
var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $http) {
$scope.rose = [{
'nome': "abc",
'costo':110
}, {
nome: "xyz",
costo: 10
}];
$scope.selectedItem1 = $scope.rose[0];// default selected item
$scope.budget0 = 60;
$scope.budget1 = $scope.budget0 - $scope.selectedItem1.costo;
$scope.change = function(){
$scope.budget1 = $scope.budget0 - $scope.selectedItem1.costo;
console.log($scope.selectedItem1);
console.log($scope.budget0 +"-"+ $scope.selectedItem1.costo +"="+$scope.budget1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
<select ng-model="selectedItem1" ng-change="change()"
ng-options="(rosa.nome+' '+rosa.costo) for rosa in rose"></select>
<br/>
{{"budget1 == "+budget1}}
</div>

Related

ng-style assign dynamic scope variable from $index

I'm trying to assign a scope variable's value to an ng-style directive but the name is not parsing.
What am I doing wrong? When you press the TEST button it should turn the text to RED but the scope variable is not parsing as it's name is dynamic. I've tried multiple different syntax which all didn't work.
Here is the html:
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
<div ng-style="{{'DynamicVariable-'+$index}}">
{{someone.name}}
</div>
</div>
</div>
controller code
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.someone = {
name: 'John'
};
$scope.items=[1,2,3,4,5,6,7,8,9];
$scope.mainId = 1;
$scope.Test=function(){
for(var i=0;i<$scope.items.length;i++){
$scope["DynamicVariable-"+i]={color:'red'};
}
console.log($scope);
};
}]);
js fiddle that doesn't work:
http://jsfiddle.net/avboivin/0qov365b/4/
It has a problem with '-', try to remove it
html:
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
<div ng-style="{{'DynamicVariable'+$index}}">
{{ someone.name }}
</div>
</div>
</div>
controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
$scope.someone = {
name: 'John'
};
$scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$scope.mainId = 1;
$scope.Test = function () {
for (var i = 0; i < $scope.items.length; i++) {
$scope["DynamicVariable" + i] = { color: 'red' };
}
console.log($scope);
};
}]);
fork

Adding ng-model directive to dynamically created input tag using AngularJs

I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.
You can create the div and input beforehand and and do not show it by using ng-if="myVar". On click make the ng-if="true".
<button ng-click="myVar = true">
In controller : $scope.myVar = false;
$scope.addInputBox = function(){
//#myForm id of your form or container boxenter code here
$('#myForm').append('<div><input type="text" name="myfieldname" value="myvalue" ng-model="model-name" /></div>');
}
Here is another solution, in which there's no need to create a div and an input explicitly. Loop through an array of elements with ng-repeat. The advantage is that you will have all the values of the inputs in that array.
angular.module('app', [])
.controller('AppController', AppController);
AppController.$inject = ['$scope'];
function AppController($scope) {
$scope.values = [];
$scope.add = function() {
$scope.values.push('');
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppController">
<button ng-click="add()">Click</button>
<div ng-repeat="value in values track by $index">
<input type="text" ng-model="values[$index]"/>
<div>{{values[$index]}}</div>
</div>
<pre>{{values}}</pre>
</div>
UPDATE. And if you want only one input, it's even simpler, using ng-show.
angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<button ng-click="show = true">Click</button>
<div ng-show="show">
<input type="text" ng-model="value"/>
<div>{{value}}</div>
</div>
</div>
You should use $compile service to link scope and your template together:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$compile', '$document' , function MyCtrl($scope, $compile, $document) {
var ctrl = this;
var inputTemplate = '<div><span ng-bind="$ctrl.testModel"></span>--<span>{{$ctrl.testModel}}</span><input type="text" name="testModel"/></div>';
ctrl.addControllDynamically = addControllDynamically;
var id = 0;
function addControllDynamically() {
var name = "testModel_" + id;
var cloned = angular.element(inputTemplate.replace(/testModel/g, name)).clone();
cloned.find('input').attr("ng-model", "$ctrl." + name); //add ng-model attribute
$document.find('[ng-app]').append($compile(cloned)($scope)); //compile and append
id++;
}
return ctrl;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl as $ctrl">
<input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
</div>
</div>
UPDATE: to add a new compiled template each time the button is clicked, we need to make a clone of the element.
UPDATE 2: The example above represents a dirty-way of manipulating the DOM from controller, which should be avoided. A better (angular-)way to solve the problem - is to create a directive with custom template and use it together with ng-repeat like this:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
var ctrl = this;
ctrl.controls = [];
ctrl.addControllDynamically = addControllDynamically;
ctrl.removeControl = removeControl;
function addControllDynamically() {
//adding control to controls array
ctrl.controls.push({ type: 'text' });
}
function removeControl(i) {
//removing controls from array
ctrl.controls.splice(i, 1);
}
return ctrl;
}])
.directive('controlTemplate', [function () {
var controlTemplate = {
restrict: 'E',
scope: {
type: '<',
ngModel: '='
},
template: "<div>" +
"<div><span ng-bind='ngModel'></span><input type='type' ng-model='ngModel'/></div>" +
"</div>"
}
return controlTemplate;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl as $ctrl">
<input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
<div ng-repeat="control in $ctrl.controls">
<control-template type="control.type" ng-model="control.value"></control-template>
</div>
</div>
</div>

I need to print array values in angular js using ng-repeat?

I'm having an array values like [0,1,5,10].
I need the output to be like this
0
1
b
b
b
5
b
b
b
b
10
For the empty values inside the array, I want to print as b. How can i do it with the ng-repeat and I dont want the static coding it want it to be dynamic.
my code is like this :
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.q = [0,1,5,10];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-repeat="i in q">{{i}}</div>
</div>
And one more thing id don't want to create a new array using array.push() method.
Please help me on this, thanks in advance.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.q = [0,1,5,10];
$scope.temp = function(){
var answer = [];
for(var i = $scope.q[0]; i <= $scope.q[$scope.q.length-1]; i++)
answer.push($scope.q.indexOf(i) == -1 ? 'b' : i);
return answer;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-repeat="i in temp() track by $index">{{i}}</div>
</div>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.q = [0, 1, 5, 10];
$scope.getNumber = function(num) {
if (num > 0) return new Array(num);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-repeat="i in q">
<div ng-repeat="j in getNumber(q[$index] - q[$index-1]-1) track by $index">b</div>
{{i}}
</div>
</div>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.q = [0,1,5,10];
$scope.empties = function(index) {
return index === 0 ? [] : new Array($scope.q[index] - $scope.q[index - 1] - 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-repeat = "i in q">
<div ng-repeat = "empty in empties($index) track by $index">b</div>
<div>{{i}}</div>
</div>
</div>
</div>

Passing data from one page to another in angular js

How do I pass data from one page to another in angular js?
I have heard about using something as services but I am not sure how to use it!
Given below is the functionality I want to execute!
On page 1:
<div class="container" ng-controller="mycontrl">
<label for="singleSelect"> Select Date </label><br>
<select nAMe="singleSelect" ng-model="dateSelect">
<option value="2/01/2015">2nd Jan</option>
<option value="3/01/2015">3rd Jan</option>
</select>
<br>
Selected date = {{dateSelect}}
<br/><br/><br/>
<label for="singleSelect"> Select time </label><br>
<select nAMe="singleSelect" ng-model="timeSelect">
<option value="9/10">9AM-10AM</option>
<option value="10/11">10AM-11AM</option>
<option value="11/12">11AM-12PM</option>
<option value="12/13">12PM-1PM</option>
<option value="13/14">1PM-2PM</option>
</select>
<button ng-click="check()">Check!</button>
<br>
Selected Time = {{timeSelect}}
<br/><br/>
User selects time and date and that is used to make call to the db and results are stored in a variable array!
Page 1 controller:
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
Now how do I send this variable $scope.therapist_list which is an array to next page which will be having a different controller and also if services is use how do define it in my application.js file
application.js:
var firstpage=angular.module('firstpage', []);
var secondpage=angular.module('secondpage', []);
To save the data that you want to transfer to another $scope or saved during the routing, you can use the services (Service). Since the service is a singleton, you can use it to store and share data.
Look at the example of jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope,NewsService) {
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{theme:"This is one new"}, {theme:"This is two new"}, {theme:"This is three new"}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
</div>
</body>
UPDATED
Showing using variable in different controller jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.newVar = {
val: ""
};
NewsService.newVar = $scope.newVar;
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope, NewsService) {
$scope.anotherVar = NewsService.newVar;
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{
theme: "This is one new"
}, {
theme: "This is two new"
}, {
theme: "This is three new"
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
<input ng-model="newVar.val">
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
<pre>newVar from ExampleOneController {{anotherVar.val}}</pre>
</div>
</body>
OK,
you write a another module ewith factory service e.g.
angular
.module('dataApp')
.factory('dataService', factory);
factory.$inject = ['$http', '$rootScope', '$q', '$log'];
function factory($http, $rootScope,$q,$log) {
var service = {
list: getList
};
service.therapist_list = null;
return service;
function getList() {
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
$log.debug("get Students service");
$http.get('/era',config).then(function successCallback(response) {
service.therapist_list = response.data;
$log.debug(response.data);
}, function errorCallback(response) {
$log.debug("error" + response);
});
}
}
Add this module as dependencies to your both page apps like
var firstpage=angular.module('firstpage', [dataApp]);
var secondpage=angular.module('secondpage', [dataApp]);
and then in your controller consume that service
.controller('homeController', ['$scope', 'dataService', function ($scope, dataService) {
}]);

angular ng-repeat and array from js

I'm tring to repeat an array in the html
html:
<div class="personWrapper" ng-repeat="message in messages">
<p>{{message}}</p>
</div>
js:
var app = angular.module('matcherApp', [ "ngRoute", "ngStorage" ]);
app.config(function($routeProvider) {
$routeProvider.when('/Messages', {
templateUrl : 'menu/messages.php',
controller : 'messagesController'
})
});
app.controller('messagesController', function($scope, $localStorage) {
console.log("im in messages page!!!");
var messagesUsers = [];
$.post("db.php", {
'messagesWindow' : "messagesWindow",
'myProfileId' : JSON.parse(localStorage.getItem("myProfileDetails")).id
}, function(data) {
data = $.parseJSON(data);
angular.forEach(data, function(key, value) {
angular.forEach(key, function(key2, value2) {
messagesUsers.push(key2.Name);
});
});
console.log(messagesUsers);
$scope.messages = messagesUsers;
}).fail(function() {
alert("error bringing messages data");
});
});
the console.log show me:
im in messages page!!!
["a","b"]
that works with all different controllers in the same app.
its not showing me on the dom any loop.
what am i doing wrong? thanks.
Works for me! Look
var app = angular.module('MessagesApp', []);
app.controller('MessagesController', function($scope) {
$scope.messages = ["a", "b"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MessagesApp" ng-controller="MessagesController">
<div class="personWrapper" ng-repeat="message in messages">
<p>{{message}}</p>
</div>
</div>
JS Code looks like below:
var app = angular.module('modelapp', []);
app.controller('ctrl', function($scope) {
$scope.emplist = ["john", "marry", "jaison"];
});
HTML Code:
<div ng-app="modelapp" ng-controller="ctrl">
<div ng-repeat="data in emplist">
<p>{{data}}</p>
</div>
</div>
It will load entire list, You can add class for div as per design, Even you can track index number also by using $index directive.

Resources