template call inside ngView not support angular directive stackoverflow - javascript

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}})

Related

AngularJS directive are not working when appended with jQuery

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>

Retrieving the value of ng-model from Directives template to Another Html file

I can't retrieve the ng-model value of my template-url from my name directive.
team-two.html
<form name="userForm" novalidate>
<div name-directive></div>
</form>
<pre>{{userForm.firstname}}</pre>
here i have name-directive inside the form and a pre tag to view as I type a value in input text of name-directive
name-directive.js
(function () {
'use strict';
var app = angular.module('app.input-form');
app.directive('nameDirective', function () {
return {
restrict: 'AE',
scope: true,
controller: function() {
var vm = this;
vm.namePattern = /^[a-zA-Z ]{1,25}$/;
},
controllerAs: 'vm',
templateUrl: '/src/client/app/input-form/name.html'
}
});
})();
in here, I have a templateUrl dont mind the other codes coz I think it not related to my concern.
name.html
<input type="text" name="firstname" class="form-control" placeholder="Enter
your first name"
ng-model="firstname"
ng-minlength="2"
ng-maxlength="20"
required
ng-pattern="vm.namePattern"/>
in here, I have a ng-model that I want to access which is the firstname..
Edit Note: I discovered that if I add $viewValue in <pre>{{userForm.firstname.$viewValue}}</pre> it works.. I get what I want.. But I think that it is not the exact solution for my problem..
Edit 2 Added link to Plunker: https://plnkr.co/edit/6glStzEq5ckZZzph2qLw?p=preview
Since you use the controllerAs in the directive need to reference that when you are accessing variables from the html.
ng-model="vm.firstname"
<input type="text" name="firstname" class="form-control" placeholder="Enter
your first name"
ng-model="vm.firstname"
ng-minlength="2"
ng-maxlength="20"
required
ng-pattern="vm.namePattern"/>

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

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.

AnjularJS get value of textboxes after button press

I set the values of textboxes via a ajax request in my controller like this :
$http({method: 'GET', url: url}).success(function(data) {
$scope.valzz = data;
$scope.company = $scope.valzz[0].Company;
});
Then in my html :
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" value="" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
This correctly puts the company name in the company textbox. But when make a change to that textbox and press the save button, the new value of the textbox isnt showing - it still gets the original. This is the button click in the controller :
$scope.saveChanges=function(){
alert($scope.company);
};
Why is $scope.company not the new value of the textbox? am i doing something wrong? (sorry if basic i am new to angular)
Try removing value=""
HTML:
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
In corresponding CONTROLLER:
$scope.saveChanges = function() {
alert($scope.company);
};
You don't have a watcher for that model.
$scope.$watch('company', function(company) {
console.log(company);
}
Or in your template, you can interpolate the value:
{{company}}
And then you can see it changing on the html page, because angular make a watcher for it behind the scene
Needed to put this.company not $scope
Please define $scope.company before $http call
app.controller('myCtrl', function($scope, $http){
$scope.company = null; // <--
$http({method: 'GET', url: url}).success(function(data) {
$scope.valzz = data;
$scope.company = $scope.valzz[0].Company;
});
}
Because, once the partials has rendered, it gets only the defined properties in $scope. After that if any property is added inside $scope it needs to call the $apply.
Hope this may help you.
I would assume that you have $scope working properly, and that you have initialized the controller in your app, as well as linked to the proper controller file. Please compare your code to what I have here, as this is working properly.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src ="controller.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="testController">
<form>
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
</form>
</div>
</body>
</html>
Controller:
(function(){
'use strict';
var app = angular.module('myApp', []);
app.controller('testController', [ '$scope', function ($scope){
$scope.saveChanges=function(){
alert($scope.company);
};
}]);
})();
Edit: Fiddle

Categories

Resources