How to get ngModel of input in the controller? - javascript

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";

Related

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 !

Updating Parent scope from child doesnot update ngrepeat

Im having problem communicating child controller with parent controller,
i hv a function that push data to parent array which is included in ngrepeat.
after pushing the parent array is appended correctly, and its length is shown correctly in parent controller, yet the ngrepeat doesnot refresh.
<div ng-controller="parentCtrl">
This works {{shared.arr.length}} <br/>
This works Too{{shared.arr|json}} <br/>
<div ng-repeat="a in shared.arr">
{{a}} This dont, it only show old data.
</div>
<section ng-contoller="childCtrl">
<button ng-click="test()">Test</button>
</section>
</div>
angular.module('testApp')
.controller('parentCtrl', function ($scope) {
$scope.shared = {arr:[1,2]};
});
.controller('childCtrl', function ($scope) {
$scope.test = function(){$scope.shared.arr.push(4);}
});
angular.module('testApp', [])
.controller('parentCtrl', ['$scope', parentCtrl])
.controller('childCtrl', ['$scope', childCtrl]);
function parentCtrl ($scope) {
$scope.shared = {
arr: [1, 2]
};
}
function childCtrl ($scope) {
$scope.test = function (arr) {
arr.push(4);
}
}
<div ng-controller="childCtrl">
<button ng-click="test(shared.arr)">Test</button>
</div>
http://jsfiddle.net/kikill/zhzb3pxh/
try this code.
there were 2 mistakes:
1) ng-controller="childCtrl", not ng-contoller="childCtrl"
2) you passed into 'test' function parent's variable. It can make a lot of errors that no so clear in this example, but it can be.
Use 'controller as' syntax. You can read about this here.
Since this code is working fine in my case, I will assume that in your code also you have done the mistake of writing controller as contoller in<ng-contoller="childCtrl"> , which is a very silly mistake :)

One time binding not working inside custom AngularJS Directive

I'm trying to wrap my head around the reason that the one-time bound value (obj.value) inside the directive in this code example is being updated?
Updating the first field will update the bound value inside the directive only once, as expected. Afterwards, inside the directive, when clicking "edit", it will also update the one-time bound value AND also update the parent scope. Updating the first field again will not change the value inside the directive.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl" ng-model-options="{updateOn: 'blur'}">
Enter value here first, then press edit:<br>
<input type="text" ng-model="t.value"><br>
<br>
Press edit, change the value and press copy:
<my-directive obj="t"></my-directive><br><br>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function() {
var directive = {};
directive.restrict = 'E';
directive.template = '<div ng-switch="edit">\
<div ng-switch-default>[{{ ::obj.value }}]<button ng-click="toggle()">edit</button></div>\
<div ng-switch-when="true">\
<input type="text" ng-model="clone.value">\
<button ng-click="copy()">copy</button>\
</div>\
</div>';
directive.scope = {
obj: '='
};
directive.controller = function($scope) {
$scope.edit = false;
$scope.toggle = function() {
$scope.edit = true;
$scope.clone = angular.copy($scope.obj);
}
$scope.copy = function() {
$scope.obj = angular.copy($scope.clone);
$scope.edit = false;
}
}
return directive;
});
myApp.controller('myCtrl', function(){
});
</script>
</body>
http://plnkr.co/edit/tbC3Ji6122gdqt4XbZpI?p=preview
In 1.3 they added a new syntax for helping with one-way binding, "::". So you just need to change your directive implementation to obj="::t".
Here's an update to your plnkr: http://plnkr.co/edit/7lsiX1ItPiQoVpJcQ6iW?p=preview
Here's a nice article that explains a bit more
It is because of ng-switch. Every time it's expression is recalculated the directive is 'redrawn'. And every time is does that the one time expression is also recalculated.
If you change your template to:
directive.template = '{{::obj | json}}<div ng-switch="edit">
etc...
you will see it won't change because it is outside of the ng-switch.

Setting data-ng-model in angular

I want to set an data-ng-model variable from a controller, but i get this error: TypeError: Cannot set property 'name' of undefined
here is the html : <input id="1" data-ng-model="name" type="text">
and the controller : $scope.name="5656";
this changes the text of the input, but not the data-ng-model="name" variable (whcich is what i need)
$('#1').val("hello");
update- controller defenition:
editApp.controller('EditController', function ($scope,$http, $routeParams, customersService,$location) {
...
});
This might be the best thing I can do to help!
http://jsfiddle.net/vcy80edg/
var editApp = angular.module('myApp',[]);
function EditController($scope) {
$scope.name = 'Hey friend!';
}

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