Unable to use ng-changeto call function - javascript

Hi had a small functionality where on change of number the value should be multiplied ..but now it is not working..
Can someone help me which is quite simple
Tag
<input type="number" class="form-control text-right" ng-model="totalPremium" ng-change="result()"></input>
Controller
$scope.result = function() => {
return $scope.totalPremium*5;
};
Thanks
Please look the jsfiddle

Module and App name is not set in your fiddle
Set module
angular.module('myapp', [])
.controller('TodoCtrl', TodoCtrl);
Set app name
<div ng-app="myapp">
Controller same as before
function TodoCtrl($scope) {
$scope.result = function() {
return $scope.totalPremium*5;
};
};
FIDDLE

Related

Execute if function if checkbox is checked angular.js

How can I execute a function when a check box is checked in angular js. I have seen a few answers on stack overflow regarding this but I cannot seem to implement them on my scenario
my code:
<div ng-controller="MyCtrl">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="thirtyDay" ng-click="changeAxis()">
Last 30 Days
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="wholeTimeline" ng-click="changeAxis()">
Whole Timeline
</label>
</div>
</div>
js.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
function changeAxis(){
if ($scope.thirtyDay) {
alert("checked 30");
}
else if($scope.wholeTimeline) {
alert("checked whole");
}
};
}
You need to place the function on the $scope, so the view will recognize it:
$scope.changeAxis = function() {
if (!$scope.thirtyDay) {
alert("checked 30");
}
else if(!$scope.wholeTimeline) {
alert("checked whole");
}
};
Another thing to notice is that when entering the function you'll get the value of the model from before the push. So if you click and it's checked, the value will still be false (hasn't been updated yet). So either use !$scope.thirtyDay or place in a $timeout.
EDIT: As Mike correctly mentioned in his comment, you would probably be better of using ng-change instead of ng-click (this way the other property won't trigger as well when interacting with the other one). I would also join the recommendation and suggest considering a different function for different properties, but I'm not sure exactly to which use you're doing this.
Here is working demo
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl" >
<div class="checkbox">
<label>
<input type="checkbox" ng-model="thirtyDay" ng-change="changeAxis1()">
Last 30 Days
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="wholeTimeline" ng-change="changeAxis2()">
Whole Timeline
</label>
</div>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', function($scope) {
$scope.changeAxis1 = function() {
if ($scope.thirtyDay) {
alert("checked 30");
$scope.wholeTimeline = false;
}
};
$scope.changeAxis2 = function() {
if($scope.wholeTimeline) {
alert("checked whole");
$scope.thirtyDay = false;
}
};
}]);
You need to add controller to myApp with this line.
myApp.controller('MyCtrl', MyCtrl);
You need to link changeAxis function to scope
$scope.changeAxis = changeAxis;
So your app.js will be something like
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
function changeAxis(){
if ($scope.thirtyDay) {
alert("checked 30");
}
else if($scope.wholeTimeline) {
alert("checked whole");
}
};
$scope.changeAxis = changeAxis;
}
I hope you have added ng-app to your html. Also please consider the ngChange suggestion mentioned in the other answer.

get ng-init value from scope

I want to get ng-init value from angular scope
controller
$scope.data={}
$scope.initvalue="myvalue";
Html
<input type="text" ng-model="data.value" ng-init="data.value= initvalue">
I want to set initvalue in input box and sent it to controller by ng-model(I want to able to modify this values so I need to make that)
Does this make sense?
http://jsfiddle.net/c7bsrenu/2/
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.data={}
$scope.initvalue="myvalue";
$scope.$watch('data.value', function(newVal, oldVal) {
console.log(newVal);
console.log(oldVal);
});
}
You can try using using $watch. Please try this demo
eg :
<div ng-controller="yourController" >
<input type="text" id="demoInput" ng-model="demoInput" ng-init="demoInput='value'" />
</div>
code in controller
var yourController = function ($scope) {
console.log('demo');
$scope.$watch("demoInput", function(){
console.log($scope.demoInput);
},1000);
}
In html
<input type="text" ng-model="data.value" ng-init="setvalue()">
In controller
$scope.data ={}
$scope.initvalue="myvalue";
$scope.setvalue= function(){
$scope.data.value = $scope.initvalue;
}
This may help for you !

Ng-model with Cookie

I'm trying to take the first example from the angular.js homepage and adding in cookie support.
This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/
It is:
<div ng-app="myApp">
<div ng-controller="MyController as mc">
<label>Name:</label>
<input type="text" ng-model="mc.user" placeholder="Enter a name here">
<hr>
<h1>Hello {{mc.user}}!</h1>
</div>
</div>
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', [function($cookies) {
this.getCookieValue = function () {
$cookies.put('user', this.user);
return $cookies.get('user');
}
this.user = this.getCookieValue();
}]);
But it's not working, ive been trying to learn angular.
Thanks
I'd suggest you create a service as such in the app module:
app.service('shareDataService', ['$cookieStore', function ($cookieStore) {
var _setAppData = function (key, data) { //userId, userName) {
$cookieStore.put(key, data);
};
var _getAppData = function (key) {
var appData = $cookieStore.get(key);
return appData;
};
return {
setAppData: _setAppData,
getAppData: _getAppData
};
}]);
Inject the shareDataService in the controller to set and get cookie value
as:
//set
var userData = { 'userId': $scope.userId, 'userName': $scope.userName };
shareDataService.setAppData('userData', userData);
//get
var sharedUserData = shareDataService.getAppData('userData');
$scope.userId = sharedUserData.userId;
$scope.userName = sharedUserData.userName;
Working Fiddle: https://jsfiddle.net/y7dxa6n8/10/
I have used the cookie service between two controllers. Fill out the text box to see how it gets utilized.
ok, examined your code once again, and here is your answer
https://jsfiddle.net/wz3kgak3/
problem - wrong syntax: notice definition of controller, not using [] as second parameter
If you are using [] in controller, you must use it this way:
myApp.controller('MyController', ['$cookies', function($cookies) {
....
}]);
this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies
problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;
problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:
$watch('user', function(newValue) {
$cookies.user = newValues;
});
or do it via some event (click, submit or i dont know where)
EDIT: full working example with $scope
https://jsfiddle.net/mwcxv820/

Binding value to select in angular js across 2 controllers

Working with angularJS I am trying to figure out a way to bind the value of a select element under the scope of controller A to use it as an argument for an ng-click call [getQuizByCampID() Function] under the scope of controller B.
My first idea was to use jquery, but I have read in the link below that using jquery is not recommended when starting with angularJS.
"Thinking in AngularJS" if I have a jQuery background?
I also read in the link below that this is performed using ng-model, the only problem is that that the example provided is all under the same controller.
and Binding value to input in Angular JS
What is the angularJS way to get the value of the select element under controller A into the function call in the select under controller B?
Price.html view
<div class="col-sm-3" ng-controller="campCtrl"> **Controller A**
<select id="selCampID" class="form-control" ng-model="campInput" >
<option ng-repeat="camp in campaigns" value="{{camp.camp_id}}">{{camp.camp_name}}</option>
</select>
</div>
<div class="col-sm-3" ng-controller="quizCtrl"> **Controller B**
<select ng-click="getQuizByCampID($('#selCampID').val())" class="form-control" ng-model="quizInput">
<option ng-controller="quizCtrl" ng-repeat="quiz in quizzesById" value="{{quiz.quiz_id}}">{{quiz.quiz_name}}</option>
</select>
</div>
App.js
var app= angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
}]);
$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
Quiz Controller
'use strict';
app.controller('quizCtrl', ['$scope','$http','loginService', function($scope,$http,loginService){
$scope.txt='Quiz';
$scope.logout=function(){
loginService.logout();
}
getQuiz(); // Load all available campaigns
function getQuiz(campID){
$http.post("js/ajax/getQuiz.php").success(function(data){
$scope.quizzes = data;
//console.log(data);
});
};
$scope.getQuizByCampID = function (campid) {
alert(campid);
$http.post("js/ajax/getQuiz.php?campid="+campid).success(function(data){
$scope.quizzesById = data;
$scope.QuizInput = "";
});
};
$scope.addQuiz = function (quizid, quizname, campid) {
console.log(quizid + quizname + campid);
$http.post("js/ajax/addQuiz.php?quizid="+quizid+"&quizname="+quizname+"&campid="+campid).success(function(data){
getQuiz();
$scope.QuizInput = "";
});
};
}])
You should store the value in a service.
example:
app.factory('SharedService', function() {
this.inputValue = null;
this.setInputValue = function(value) {
this.inputValue = value;
}
this.getInputValue = function() {
return this.inputValue;
}
return this;
});
Example on Plunkr
Read: AngularJS Docs on services
or check this Egghead.io video
You should use service to store the value.
This is how to do that:
Share data between AngularJS controllers

Dynamically assign ng-model

I'm trying to generate a set of check-boxes from an object array. I'm aiming to have the check-boxes dynamically map their ng-model to a property of the new object that will be submitted into the array.
What I had in mind is something like
<li ng-repeat="item in items">
<label>{{item.name}}</label>
<input type="checkbox" ng-model="newObject.{{item.name}}">
</li>
This doesn't work as can be seen on this JSFiddle:
http://jsfiddle.net/GreenGeorge/NKjXB/2/
Can anybody help?
This should give you desired results:
<input type="checkbox" ng-model="newObject[item.name]">
Here is a working plunk: http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR?p=preview
EDIT
As correctly noted in the comments using this with ng-change requires a "dummy" ng-model to be present beforehand. It should however be noted that apparently with 1.3 the required options have been provided by the framework. Please check out https://stackoverflow.com/a/28365515/3497830 below!
/EDIT
Just in case you are like me stumbling over a simple case while having a more complex task, this is the solution I came up with for dynamically binding arbitrary expressions to ng-model: http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p=preview
Method: I created a directive dynamicModel that takes a standard angular expression, evaluates it and links the result to the scope via ng-model and $compile.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
app.directive('dynamicModel', ['$compile', function ($compile) {
return {
'link': function(scope, element, attrs) {
scope.$watch(attrs.dynamicModel, function(dynamicModel) {
if (attrs.ngModel == dynamicModel || !dynamicModel) return;
element.attr('ng-model', dynamicModel);
if (dynamicModel == '') {
element.removeAttr('ng-model');
}
// Unbind all previous event handlers, this is
// necessary to remove previously linked models.
element.unbind();
$compile(element)(scope);
});
}
};
}]);
Usage is simply dynamic-model="angularExpression" where angularExpression results in a string that is used as the expression for ng-model.
I hope this saves someone the headache of having to come up with this solution.
Regards,
Justus
With Angular 1.3, you can use ng-model-options directive to dynamically assign the model, or bind to an expression.
Here is a plunkr: http://plnkr.co/edit/65EBiySUc1iWCWG6Ov98?p=preview
<input type="text" ng-model="name"><br>
<input type="text" ng-model="user.name"
ng-model-options="{ getterSetter: true }">
More info on ngModelOptions here: https://docs.angularjs.org/api/ng/directive/ngModelOptions
This is my approach to support deeper expression, e.g. 'model.level1.level2.value'
<input class="form-control" ng-model="Utility.safePath(model, item.modelPath).value">
where item.modelPath = 'level1.level2' and
Utility(model, 'level1.level2') is the utility function that returns model.level1.level2
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="priceForm" ng-submit="submitPriceForm()">
<div ng-repeat="x in [].constructor(9) track by $index">
<label>
Person {{$index+1}} <span class="warning-text">*</span>
</label>
<input type="number" class="form-control" name="person{{$index+1}}" ng-model="price['person'+($index+1)]" />
</div>
<button>Save</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.price = [];
$scope.submitPriceForm = function () {
//objects be like $scope.price=[{person1:value},{person2:value}....]
console.log($scope.price);
}
});
</script>
</body>
</html>

Categories

Resources