Cannot access value of ng-model variable of bind-unsafe-html - javascript

Inside showdetailsOfInside() function value of ng-model variable namein and agein that is inside bind-unsafe-html coming undefined however i have filled text contents into it.I can get value through jquery but is there any way to do it through angular js.
<body ng-controller="AppController" class="container">
Name <input type="text" name="name" ng-model="name" /><br>
Age <input type="text" name="age" ng-model="age"/><br>
<button type="button" class="btn btn-primary" ng-click="showdetailsOfInside()">showdetailsOfInside</button><br>
<div bind-unsafe-html="primaryData"></div>
<body>
Content of bind-unsafe-html="primaryData"
<button type="button" class="btn btn-primary" ng-click="shownName()">inside Basic</button><br>
<button type="button" class="btn btn-primary" ng-click="showAge()">inside Primary</button><br>
Name inside <input type="text" name="namein" ng-model="namein" id="nameinside"/><br>
Age indise :: <input type="text" name="agein" ng-model="agein" id="ageinside"/><br>
Code of bind-unsafe-html directive
dynamicContentApp.directive('bindUnsafeHtml', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'bindUnsafeHtml' expression for changes
return scope.$eval(attrs.bindUnsafeHtml);
},
function(value) {
// when the 'bindUnsafeHtml' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}]);

If i'm right, that's ng-bind-unsafe-html="primaryData"

dynamicContentApp.directive('bindUnsafeHtml', ['$compile', function ($compile) {
return {
link: function (scope, element, attrs) {
//code goes here
};
}
}]);

Related

AngularJS directive for <input type="file"> validation

I'm trying to make a directive able to handle an <input type="file"> validation inside a <form> given that AngularJS doesn't have support for this...It kind of works to check if a file is selected, but I also have a <textarea> in the form so when I select a file the form gets state $valid=true, but just by typing into the <textarea> makes the form become $valid=false even though I haven't set a validation for the <textarea>. Why does this happen? How can I fix it?. Here is a simplified example to illustrate the problem:
My app.js file:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
app.directive('validFile', function () {
return {
restrict: "A",
require: '^form',
link: function (scope,elem,attrs, ctrl) {
elem.bind("change", function(e) {
console.log("change");
scope.$apply(function(){
ctrl.$valid=true;
ctrl.$invalid=false;
});
});
}
};
});
My index.html file:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-form="myForm" >
<input ng-model="filename" valid-file required type="file"/>
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i> Ok</button>
<div >
<textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
</div>
<p>
Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
<br>Selected file: {{filename}}
<br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
</p>
</div>
</body>
</html>
there's a working plnkr of what I just said:
http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview
A quick hack would be to just take the text-area out of the ng-form like this -
<div ng-form="myForm">
<input id="userUpload" ng-model="filename" archivo-valido
name="userUpload" required type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
</div>
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
<i class="icon-white icon-ok"></i> Ok
</button>
Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -
ERRONEOUS
scope.$apply(function(){
if(true){ // will always evaluate to true. Why the else part then?
ctrl.$valid=true;
ctrl.$invalid=false;
}else{
ctrl.$valid=false;
}
});
A better approach would be to write Custom Validators on each of your ngModels like this -
app.directive('archivoValido', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.archivoValido = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
// your custom validation here
...
// it is invalid
return false;
};
}
};
});

Directives interfering with each other

I have 2 directives that are on the same level as follows:
function signUpForm(djangoAuth, Validate){
return{
restrict:'A',
controller:["$rootScope","$scope",function($rootScope, $scope){
$scope.submitFunction = function(formData){
//do stuff
}
}]
}}
function signInForm(djangoAuth, Validate){
return{
restrict:'A',
controller:["$rootScope","$scope",function($rootScope, $scope){
$scope.submitFunction = function(formData){
//do stuff
}
}]
}}
My HTML is as follows:
<div>
<div class="email_log_container">
<form name="signup_form" class="signup_form" sign-up-form
novalidate ng-submit="submitFunction(signup_form)">
<input type="submit" name="submit" value="Submit" >
</form>
</div>
<div class="email_log_container">
<form name="signin_form" class="signin_form" sign-in-form
novalidate ng-submit="submitFunction(signin_form)">
<input type="submit" name="submit" value="Submit" >
</form>
</div>
</div>
The problem is that when I click the submit button on the second form, it actually submits the first form which results in errors. So I went on to add isolate scopes to the directives, now what happens is that the functions and attributes attached to $scope in the controller are not being picked up now. For example ng-submit does not know about the submitFunction within the controller.
Can anyone help me with ideas on how to stop these two directives from interfering with each other?
While you are using a controller but no template for your directive this will not work. Try it like in this runnable demo fiddle and add the form as a template into your directive. In that way you will be able to handle all the $scope goodness in your directive controller itself. The template itself will be compiled and uses the directive controller.
View
<div ng-controller="MyCtrl">
<div class="email_log_container">
<sign-in-form></sign-in-form>
</div>
</div>
AngularJS application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
});
myApp.directive('signInForm', function signInForm(){
return{
restrict:'E',
replace: true,
template: '<form name="signin_form" class="signin_form" sign-in-form novalidate ng-submit="submitFunction(signin_form)"><input type="submit" name="submit" value="Submit" ></form>',
controller:["$rootScope","$scope",function($rootScope, $scope){
$scope.submitFunction = function(formData){
//do stuff
console.log('sdfsdfd');
}
}]
}});

How do I fire the enter keypress event of <input type="text"> programmatically in angular.js?

I have this <input type="text"> element whose enter keypress event I want to fire via the ng-click of another button.
i.e.,
Lets say :
<button ng-click="clickEvent()"></button>
<input type="text" id="textbox"></input>
Plnkr is here : http://plnkr.co/edit/tEVoHAAcyqQzWpc9iYpo?p=preview
Please help!
You can achieve this by creating angular directive. JSFiddle for reference - Demo
See the console after click on Click Me ! button. Hope this will help!
<body ng-app="myApp" ng-controller="myController">
<h1>Hello JSFiddle!</h1>
<button id="btnClick" ng-click="clicked()" capture-keypress>Click Me !</button>
<input ng-keydown="keypress($event)" id="txtInput">
</body>
app.controller('myController', function($scope) {
$scope.keypress = function($event) {
console.log('Key Event Fired');
};
});
app.directive('captureKeypress', function($timeout) {
return {
scope: true,
link: function(scope, element, attrs) {
scope.clicked = function() {
$timeout(function() {
element.siblings('#txtInput').trigger('keydown');
})
}
}
}
});

How do you find first visible element with jqlite under AngularJS?

So, I have the following Angular directive to autofocus first input field on the current page of my Ionic application. It works great when the first field isn't hidden. But, if it's hidden by ng-hide, logic fails. So need to modify the element selector to find just for visible elements in my directive.
angular.module('myApp').directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
$timeout(function() {
element.find('label')[0].focus();
}, 150);
}
};
});
Using above directive on a form element as follows,
<form name="signinForm" ng-submit="signinForm.$valid && doSignin(credentials)" novalidate focus-me>
So how should I change my jQLite find query to just look for the visible element? The find lookup is limited by tag name as per docs.
You can write something like this:
element[0].querySelector('input:not(.ng-hide)').focus();
jQLite only allows selecting by tag name. So we can use the pure Javascript version i.e. querySelector along with using :not selector.
See a working example below:
angular.module('myApp', [])
.directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
$timeout(function() {
element[0].querySelector('input:not(.ng-hide)').focus();
}, 150);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form focus-me ng-app="myApp">
<input type="text" name="firstName" ng-show="false" />
<input type="text" name="lastName" ng-show="true" />
<input type="text" name="email" />
</form>

Angular.JS: Data not getting updated in Angular for Popups

I am trying to do a Pop-up in Angular.js with a table, where there is an option to click in a particular cell in a row which gives a pop-up. Below is the code snip.
Html code
<table class="table table-bordered">
<tr><th>Number</th><th>Comment</th></tr><tr ng-repeat="col in Data|filter:search1"><td>{{col.cd}}</td><td><div ng-controller="igCtrl">
Comment
<ig-comment></ig-comment>
</div></td></tr></table>
Controller
function igCtrl($scope) {
$scope.addComment = function (col) {
$scope.cdn="";
$scope.cdn = col;
console.log("testing"+$scope.cdn);
$scope.check = true;
if ($scope.check) {
$("#comment").modal('show');
};
};}
Directive
app.directive('igComment', function () {
return {
restrict: 'E',
replace: true,
template:'<div class="row">
<div class="modal fade" id="comment" aria-hidden = "true" >
<div class = "modal-dialog" style="width:300px;height:600px;">
<form class="form-horizontal" name="form" ng-submit = "submit()" novalidate="novalidate">
<div class = "modal-content" >
<div class = "modal-header">
Data is :{{cdn}}
<input ng-disabled="form.$invalid" type="submit" class="btn btn-primary" id="submit" ng-click="submit()" value="Submit"></input >
<input type="button" class="btn btn-primary" data-dismiss="modal" value="Cancel" ng-click="cancel()"></input>
</div>
</div >
</form>
</div >
</div>
</div>'
};
});
Data for this table is coming from the database. The variable cdn in the controller is getting updated and the console.log statement in the controller gives correct output.
But cdn in the directive is not getting updated and hence not showing rite results in the pop-up.
How to rectify this?
Thanks
I'd use an isolated scope for this.
e.g.:
<ig-comment cdn="cdn"></ig-comment>
* this takes the "cdn" value from the controller's scope
and in the directive:
return {
restrict: 'E',
replace: true,
scope: { cdn: '=' } // this assigns the "cdn" from the directive attribute above
// to the directive isolated scope (under the same name)
...
The rest seems fine (ignoring the unfortunate jquery mix) and should work.

Categories

Resources