AngularJS directive are not working when appended with jQuery - javascript

i am appending given below html form returned from server side in response of ajax call
<div ng-app="submitExample" >
<form action="shan" ng-submit="submit()" ng-controller="ExampleController" id="account_info_modal">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</div>
here angular js directive are not working when appending form using ajax but when form is on page then angular js code working properly my angular js script is given below
(function() {
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.submit = function() {
alert("hello submit");
};
}]);
})();
give below function i am using to append html form
function show_account_info_modal(param)
{
var id=$(".jstree-clicked").parent().attr('id');
var name=$(param).attr('name');
$.ajax({
type: 'get',
url: '<?= admin_url('Chart_of_accounts/get_account_info_modal'); ?>',
data: { account_id:id,name:name },
success: function (data)
{
$("#account_info_modal").html(data)
}
});
}

You need to use $compile service when appending element.
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
As per your code use
$("#account_info_modal").html($compile(data)($scope))
Here is an example
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', '$compile',
function($scope, $compile) {
$scope.click = function() {
console.log($scope.text)
}
//Append element dynamically
var html = $compile('<input type="text" ng-model="text" name="text" /><button type="button" ng-click="click()">Click Me</button>')($scope);
angular.element(document.querySelector('#x')).append(html);
}
]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div id="x">
</div>
</div>
</div>

Related

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 to can I define scope to HTML block in Angular?

I have a very large form in my application page, and I have a JSON variable, where I saving all form data in it, and I'm using controllerAs expression.
<form>
<input type="text" data-ng-model="ctrl.myJSON.name"/>
<input type="text" data-ng-model="ctrl.myJSON.old"/>
<input type="text" data-ng-model="ctrl.myJSON.address"/>
<input type="text" data-ng-model="ctrl.myJSON.email"/>
<input type="text" data-ng-model="ctrl.myJSON.phone"/>
<!-- and many more... -->
</form>
How to can I define myJSON as the form scope, for no need repeat this variable many time in all fields?
you can use angular extend to copy the json data to $scope. And then, you can use directly:
.controller('YourController', function($scope) {
$scope.readData = function() {
// replace with your read data function
var myJSON = { name: 'test' };
angular.extend($scope, myJSON);
}
}
after that, the variables will work directly:
<input type="text" data-ng-model="name"/>
Wrap the form inside a separate, dedicated controller FormController and copy the myJson key-value-pairs to its $scope.
This is possible in the later versions of Angular using scope inheritance/nested scopes.
HTML
<div ng-controller="MainController">
<form ng-controller="FormController">
<input type="text" data-ng-model="name"/>
<input type="text" data-ng-model="old"/>
<input type="text" data-ng-model="address"/>
<input type="text" data-ng-model="email"/>
<input type="text" data-ng-model="phone"/>
<!-- and many more... -->
</form>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('MainController', ['$scope', function($scope) {
// other logic goes here
}]);
myApp.controller('FormController', ['$scope', function($scope) {
// Initialize myJson by loading its data from a service
angular.extend($scope, myJson);
}]);
JSFiddle: https://jsfiddle.net/206redxb/5

Pass ng-model value into ng-click failed

How to pass ng-model's value to ng-click?
<div ng-controller="TodoCtrl">
<input type="text" ng-model="username">
<button class="btn-primary" type="submit" ng-click="submit(username)">submit</button>
</div>
Why in my submit function it doesn't get the username's value?
http://jsfiddle.net/U3pVM/26604/
You don't need to pass username as a parameter to your function. You can get the username value from $scope.username in your function already.
Here is the correct answer:
Corrected the 'username' in alert and also while defining the method should not use paranthesis $scope.submit = function() { }
var app = angular.module('myApp', []);
app.controller('TodoCtrl', function($scope) {
$scope.submit = function(username){
alert(username) //get username here
}
});
Also you have specify the module name in the html:
<div ng-app='myApp'>
<div ng-controller="TodoCtrl">
<input type="text" ng-model="username">
<button class="btn-primary" type="submit" ng-click="submit(username)">submit</button>
</div>
</div>
There are some missings and spelling errors.
var app = angular.module('myApp', []);
app.controller('TodoCtrl', function($scope) {
$scope.submit = function(username){
alert(username) //get username here
console.log("username", username)
}
});
<div ng-app ="myApp">
<div ng-controller="TodoCtrl">
<input type="text" ng-model="username">
<button class="btn-primary" type="submit" ng-click="submit(username)">submit</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
Here is the updated Demo
There are some errors in your code
Below, find the fixed code
HTML
<div ng-app="myApp">
<div ng-controller="TodoCtrl">
<input type="text" ng-model="username">
<button class="btn-primary" type="submit" ng-click="submit(username)">submit</button>
</div>
</div>
CONTROLLER
var app = angular.module('myApp', []);
app.controller('TodoCtrl', function($scope) {
$scope.submit = function(username){
alert(userame) //get username here
}
});
there are errors in your fiddle
please update your submit method as below
$scope.submit = function(username){
alert(username) //get username here
}
You are using parenthesis () after $scope.submit which is invalid declaration for function.
also give name to ng-app like
<div ng-app="myApp">
and inside alert give variable name properly , you have done spelling mistake in variable name.
There is a missing decleration of your ng-app attribute. Try this:
<div ng-app='myApp'>
In addition, correct your function name and argument typo:
$scope.submit = function(username){
alert(username)
}
This is an example of your requirement. Just test on my snippet sending value on alert().
var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.submit = function(mymdl){
alert(mymdl);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="mymdl"/>
<button ng-click="submit(mymdl)">Submit</button>
</div>

ng-model value of input text box is undefined inside angularjs controller when set dynamically through javascript

In my HTML Page i am setting an input text box value not by typing but through JavaScript and then when I am fetching that value using AngularJS inside the controller using scope, then it's showing undefined....
Below is my code:-->
<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="someForm" name="someForm">
First Name: <input type="text" id="fname" ng-model="user.firstname" ng-model-options="{updateOn: 'change'}" />
Last Name: <input type="text" id="lname" ng-model="user.lastname" ng-model-options="{updateOn: 'change'}" />
<input id="getUser" type="submit" ng-click="getUserName(user)" value="Get User" />
<button ng-click="resetForm(user)">RESET</button>
</form>
</div>
<script>
$('#getUser').on('click', function(){
//$("getUser").on('click', function(){
//alert("First Name "+$("#fname").val());
$("#lname").val($("#fname").val());
alert("Last Name set to "+$("#lname").val());
// });
});
</script>
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.getUserName = function(user)
{
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
$scope.resetForm = function(user) {
//Even when you use form = {} it does not work
angular.copy({},user);
}
});
</script>
</body>
</html>
After clicking Get User Button, first the lastname field value is set through JQuery then AngularJS controller is called in which the ng-model value is undefined. I am unable to understand this. What is the solution or workaround for this type of scenario where the input text field value is set dynamically through JavaScript or JQuery and fetched and used using AngularJS Model and Controller.
Looks like you have a typo at ng-model="user.lasttname"
<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="someForm" name="someForm">
First Name: <input type="text" id="fname" ng-model="user.firstname" ng-model-options="{updateOn: 'change'}" />
Last Name: <input type="text" id="lname" ng-model="user.lastname" ng-model-options="{updateOn: 'change blur'}" />
<input id="getUser" type="button" ng-click="getUserName(user)" value="Get User" />
<input id="getUser2" type="button" ng-click="getUserName(user)" value="Get User" />
<button ng-click="resetForm(user)">RESET</button>
</form>
</div>
<script>
$('#getUser').on('click', function(){
var element = angular.element($('#someForm'));
element.scope().user.lastname = $("#fname").val();
});
</script>
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.getUserName = function()
{
console.log("User: "+ JSON.stringify($scope.user));
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
$scope.resetForm = function(user) {
//Even when you use form = {} it does not work
// angular.copy({},user);
}
});
</script>
</body>
</html>
Add this in angularjs code:-
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {}; // Initiate this
$scope.getUserName = function(user)
{
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
});
Of course!!! If you want the binding (HTML <--> JavaScript) you must respect the rules of Angular. What you need to do is to update the ng-model being defined for the input box. So, add to your input box: ng-model="blabla" and within your JavaScript: $scope.blabla = <value>.
Correction: You do have the ng-model in the input, but still miss the assignment within your javascript code.

template call inside ngView not support angular directive stackoverflow

My question involves how to use AngularJS directives in the template called inside ngView in an AngularJS application.
Define :
The application is single-page, so it loads an index.html that contains a div element(template url) in the DOM with the ng-view attribute.
Main Page(index.html) :
<html data-ng-app="App" data-ng-controller="AppCtrl">
<head>
<title>Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<!-- primary nav -->
Page 1
Page 2
Page 3
<!-- display the view -->
<div ng-view>
</div>
</body>
</html>
app.js :
angular.module('App', [])
.controller('AppCtrl', function($rootScope, appLoading) {
$rootScope.topScope = $rootScope;
$rootScope.$on('$routeChangeStart', function() {
appLoading.loading();
});
})
.config(function($routeProvider) {
$routeProvider.when('/page1', {
controller : 'Page1Ctrl',
templateUrl : 'page1.html'
})
.when('/page2', {
controller : 'Page2Ctrl',
templateUrl : 'page2.html'
})
.when('/page3', {
controller : 'Page3Ctrl',
templateUrl : 'page3.html'
})
.otherwise({
redirectTo: '/home'
});
})
page1.html :
<div class="form">
<form class="login-profile" method="post" action="" name="editfrm">
<input type="text" name="email" value="" id="txtemail" data-ng-model="email" required>
<input type="password" name="password" value="" id="txtpassword" data-ng-model="password" required>
<input type="button" value="Save" name="submit">
</form>
</div>
Problem :
Template Url called inside the ngView not supported any AngularJS deirective.
data-ng-model="email" & data-ng-model="password" not working when called in the ngView on click the link Page 1
Any help will be appreciated. Thanks
Without seeing code for your Page1Ctrl it's hard to tell but it seems like you are trying to share data between controllers using $rootScope, no?
Well, just don't. Use either $routeParams or a service for that purpose. For example:
// app controller
.controller('AppCtrl', function(User) {
User.set({email:'email', password:'password'}); // set user
})
// page 1 controller
.controller('Page1Ctrl', function($scope, User) {
$scope.user = User.get(); // get user
})
// user service
.service('User', function() {
var user = null;
return {
get: function() {
return user;
},
set: function(val) {
user = val;
}
};
});
and related HTML
<input type="text"
name="email"
data-ng-model="user.email"
required>
<input type="password"
name="password"
data-ng-model="user.password"
required>
When you click on Page 1, it loads Page1Ctrl and page1.html. Are you sure you are not able to access $scope.email and $scope.password in Page1Ctrl.
It should be accessible, if not then try to create a model object as follows:
$scope.LoginProfile = {
email: '',
password: ''
}
and use this LoginProfile object in your page1.html like this LoginProfile.email and LoginProfile.password.
PS: Try to interpolate on html so you can view values, (e.g. LoginProfile: {{LoginProfile}})

Categories

Resources