get ng-init value from scope - javascript

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 !

Related

Unable to use ng-changeto call function

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

Angular filter: how to get filter complete callback?

I am looking for an callback function after $filter filter completes the filtering the data
HTML
<input type="text" ng-model="searchvalue">
<span ng-click="searchbtn()">Search</span>
JS
$scope.searchbtn = function() {
$scope.loading = true;
$scope.mysearchvalue = $scope.searchvalue;
}
When user enters keyword my data will be filtered and i need a callback function after filtering the data.
i have tried using "DOMSubtreeModified" but returning continues logs
var myElement = angular.element(document.getElementById("mycontent"));
myElement.bind("DOMSubtreeModified", function() {
console.log("keep outputting this message");
});
As said in my comment, why not just use a little delay (debounce) and filter results in controller w/o separate input button. Consider
HTML template
<body ng-controller="MainCtrl">
<pre ng-bind="filteredData | json"></pre>
<input type="text" ng-model="search" ng-model-options="{debounce:250}">
</body>
JavaScript
angular.module('app', [])
.controller('MainCtrl', function($scope, $filter) {
$scope.data = [{text:'aa'},{text:'ab'}];
$scope.$watch('search', function(val) {
$scope.filteredData = $filter('filter')($scope.data, val);
});
});

How to get ngModel of input in the controller?

Consider I have controller and input with ngModel .
I want to get this ngModel in the controller and execute $setViewValue on it .
The snippet is attach . The trying to execute - $setViewValue gives error -
TypeError: Cannot set property '$setViewValue' of undefined
var myAppModule = angular.module('myApp', []);
myAppModule.controller('myCtrl',function ($scope) {
$scope.entityMail.$setViewValue("blabla#aaa.com");
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app="myApp">
<form ng-controller="myCtrl">
Mail <input type="text" ng-model="entityMail">
</form>
</div>
How to get this ngModel correctly and execute $setViewValue on it ?
Edit:
I edited my code . I must use it with $setViewValue.
var myAppModule = angular.module('myApp', []);
myAppModule.controller('myCtrl',function ($scope,$interval) {
$scope.entityMail = "blabla#aaa.com";
});
First you have to declared $scope.entityMail as a object, then only you can apply $setViewValue in this.
var myAppModule = angular.module('myApp', []);
myAppModule.controller('myCtrl',function ($scope) {
$scope.entityMail = {};
$scope.entityMail.$setViewValue("blabla#aaa.com");
});
Instead of $setViewValue you can directly assign the value to the ngModel
$scope.entityMail = "blabla#aaa.com";

Define default values in angularjs form, validation doesnt'work

I'm lost about define default values in my form : http://1ffa3ba638.url-de-test.ws/zombieReport/partials/popup.html
validation doesnt'work too...
/*********************************** SubmitCtrl ***********************************/
app.controller('SubmitCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
/* data pre-define : date & url for test */
$scope.myForm = {};
$scope.myForm.date = new Date();
$scope.myForm.url = "prout";
/* ng-show things */
$scope.successMailZR = false;
$scope.errorMailZR = false;
$scope.send = function() {
if ($scope.myForm.$valid) {
alert('ok');
}
};
}]);
What is the correct way for define default values ?
edit :
for url i do it like this :
<input type="text" class="form-control" name="url" placeholder="{{myForm.url}}" value="{{myForm.url}}" ng-model="myForm.url" readonly="readonly" />
it's not working
There is a conflict between a binding model $scope.myForm and the form name <form name="myForm".
Angular will assign the form's controller into the $scope as its name i.e. $scope.myForm and that override what you have initialized.
Change your form name or the binding variable to have a different name.
In HTML:
<input value="default">
Or using Angular's ng-model:
<div ng-controller="YourCtrl">
<input ng-model="value">
</div>
function YourCtrl($scope) {
$scope.value = 'default';
}

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