modalInstance is undefined in Angular js - javascript

ModalInstance data is getting NULL in importing controller.
I have changed modelInstance name also.But dint work out.
here am adding my code,
SaveController.js
scope.open = function (_data) { //data is present
var modalInstanceData = modal.open({
controller: "PopUpController",
templateUrl: 'myModalContent.html',
resolve: {
data: function()
{
return _data; // values are present here
}
}
});
};
PopUpController.js
angular.module('user').controller('PopUpController',
['$scope','$state','$uibModalInstance',
function(scope,state,modalInstanceData,data) {
data={};
scope.data = data;
farmBid.produceValue = scope.data.produceId; //value is present here
}])
Html
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-body">
<input type="text" name="produceValue" ng-model="farmBid.produceValue" />
<!-- But here its not prefilling the data-->
<input type="submit" ng-click="generate(farmBid)">
</div>
</script>
Modal data values are not being visible in HTML page
Please help

You should pass the parameters in right order and should match, you are missing 'data'
angular.module('user').controller('PopUpController',
['$scope','$state','$uibModalInstance','data',
function(scope,state,modalInstanceData,data) {

Related

AngularJS: Trying to get data from variable

cartController in AngularJS:
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$scope.refreshCart = function() {
$http.get('http://localhost:8080/rest/cart')
.success(function(response) {
$scope.items = response.data;
});
};
$scope.removeFromCart = function(productId) {
$http.delete('/delete/' + productId)
.success(function (data) {
$scope.refreshCart();
});
};
$scope.addToCart = function(productId) {
$http.put('/add/'+ productId)
.then(function(response) {
$scope.refreshCart();
});
};
});
First HTML file (here everything works):
<a href = "#" type="button" class="btn btn-info" th:attr="
ng-click='addToCart(' + ${product.id} + ')'" data-toggle="modal" data-target="#myModal">
Add to cart</a>
Second HTML file:
<html lang="en" xmlns:th="http://www.thymeleaf.org" ng-app="demo">
<script src="http://localhost:8080/cartController.js"></script>
<body ng-controller="Hello">
(...)
<tbody ng-repeat="item in items.cartItemList">
<div class="row">
<h4 class="nomargin">{{item.product.name}}</h4>
<p>{{item.product.description}}</p>
</div>
<td data-th="Price">{{item.price}} PLN</td>
<td data-th="Quantity">{{item.quantity}}</td>
</tbody>
(...)
So what i need to do is:
1) Hit the button in first HTML file, and load JSON to $scope.items (it works).
2) Show the second HTML file, load JSON from $scope.items, and view this JSON to user.
But when I get the second HTML file and try to show data, the $scope.items is empty. Can you help pleae ?
Do you get console errors in your browser? Maybe you have to define items on the controller as empty array like in the example below ...
.controller('Hello', function($scope, $http) {
//define empty array
$scope.items = [];
$scope.refreshCart = function() {
$http.get('http://localhost:8080/rest/cart')
.success(function(response) {
$scope.items = response.data;
});
};
//...
}
I would suggest you to use broadcast and emit. Pass data between the controllers using these. You should use $broadcast if you want to pass data from parent controller to child controller. And emit if the other way around.

Dynamic property on JavaScript object getting null

I'm trying to set the dynamic property on a javascript object using the ng-model. But I'm unable to create it as I always get null for that property. I have different ways to copy the value from the variable self.username to self.params javascript object in the below code.
Please see this plnkr
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.2.26/angular.js"></script>
<script src="https://code.angularjs.org/1.2.26/angular-route.min.js">
</script>
<script src="app.js"></script>
<script src="routes.js"></script>
</head>
<body>
Carriers
<div class="mainContainer" ng-view></div>
</body>
</html>
routes.js
myApp.config(function($routeProvider) {
$routeProvider
.when('/carriers', {
templateUrl: 'carriers.html',
controller: 'MainCtrl',
controllerAs: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Carriers.html
<input type="text" placeholder="username" ng-model="mainCtrl.username" />
<button ng-click="mainCtrl.login()">Login</button>
app.js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function() {
var self = this;
self.username = '';
self.login = login;
self.params = {
username: self.username //doesnt work
};
//self.params.username=angular.copy(self.username); //doesnt work
//self.params['username']=self.username; //doesnt work
function login() {
// alert(self.username);
console.dir(self.username); // works
console.dir(self.params); // username:'' getting empty string for username property
}
});
The value does not update because you created a new object and set the value of self.params.username to the value of self.params. self.params.username does not reference self.params it was just set from the value when the object was created.
If you want to bind self.params.username to the input then you can change your input model to:
<input type="text" placeholder="username" ng-model="mainCtrl.params.username" />
Another alternative is to watch self.username and set the value of self.params.username to the new value using $watch
// watch mainCtrl.username for any changes
$scope.$watch('mainCtrl.username', function(newValue, oldValue) {
// set self.params.username from the new value
self.params.username = newValue;
});

Getting controller name from $parent in AngularJS

I have converted one of my Angular controllers to Controller As syntax, but I am having trouble getting an ng-grid template to play nicely.
The controller has a function called edit user that looks like this
self.editUser = function (user_data) {
var modalInstance = $modal.open({
templateUrl: '/admin/views/adminuser.html',
controller: 'AdminUserController',
resolve: {
user_data: function () {
return user_data;
}
}
});
modalInstance.result.then(function () {
self.myQueryData.refresh = !self.myQueryData.refresh;
});
};
the ng-grid template looks like this
<div class="ngCellText" ng-class="col.colIndex()">
<a ng-click="$parent.$parent.$parent.$parent.editUser({user_id:row.entity.id, first_name:row.entity.first_name, last_name:row.entity.last_name, email:row.entity.email})">
<span ng-cell-text translate>Edit</span>
</a>
</div>
and my route looks like this
.when('/admin/settings', {
templateUrl: '/admin/views/settings.html',
controller: 'SettingsController as sc',
})
So the problem is in the template when I call
$parent.$parent.$parent.$parent.editUser
it doesn't know what I am talking about unless I include the controller name like
$parent.$parent.$parent.$parent.sc.editUser,
then it works great. However I don't want to bind this template directly to the sc controller. How can I call the editUser without using the controller name?
I was hoping there would be a function on the $parent that would supply the function name like
$parent.$parent.$parent.$parent.getController().editUser
Any suggestions?
You can call functions on parent scope directly without referring to $parent. Because you might get in to trouble later when you modify your view structure.
example:
<div ng-app="MyApp">
<div ng-controller="MyController">
{{myMessage}}
<div ng-controller="MyController2">
<div ng-controller="MyController3">
<div ng-controller="MyController4">
<button id="myButton" ng-click="setMessage('second')">Press</button>
</div>
</div>
</div>
<script>
angular.module('MyApp', [])
.controller('MyController', function($scope) {
$scope.myMessage = "First";
$scope.setMessage = function(msg) {
$scope.myMessage = msg;
};
}).controller('MyController2', function($scope) {
}).controller('MyController3', function($scope) {
}).controller('MyController4', function($scope) {
});
</script>
</div>
</div>
Or else you can use angular $broadcast
Since you are using controllerAs syntax, you can address your controller by the alias, so the actual template line will look like this:
<a ng-click="sc.editUser({user_id:row.entity.id, first_name:row.entity.first_name, last_name:row.entity.last_name, email:row.entity.email})">

Angular-UI Bootstrap : pass value from Trigger's button to Modal's button

Need some guidance. I am using angular-ui-bootstrap with php and mysql. I want to pass value from list of link (generated from php mysql) to modal button each time modal loads.
HTML
// Below link is while-loop with php-mysql result
Issue
<script type="text/ng-template" id="SubmissionReminder.html">
<div class="modal-header">
<h3 class="modal-title">Submission Work Order Request</h3>
</div>
<div class="modal-body">
Please ensure quotation(s) or any document(s) related to this Work Order is ready for Procurement Unit to proceed accordingly.
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
Submit
</div>
</script>
JS
app.controller('userWOController', function ($scope, $modal) {
$scope.animationsEnabled = true;
$scope.open = function () {
$scope.items = [];
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl : 'SubmissionReminder.html',
controller: 'SubmissionReminder'
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
app.controller('SubmissionReminder', function ($scope, $modalInstance) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
I'm stuck on how to pass value from trigger (a href) to modal button (a href).
You can send data into modal controller pass through resolve object:
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl : 'SubmissionReminder.html',
controller: 'SubmissionReminder',
resolve: {
refno: function () {
return {refno: $scope.refno};
}
}
});
Then get resolved refno from modal controller:
app.controller('SubmissionReminder', function ($scope, $modalInstance, refno) {
$scope.refno = refno().refno;
...
}

AngularJS Factory loading data on each click

Plunker
There are a lot of files, so perhaps you Angular aficionados will understand my explanation, or be able to follow the plunker I've provided above.
I'm creating a demo to modularize a webpage. Even the main content of the page will be in another template file. In the main content view, there's a table of links, the link opens an angular-bootstrap modal (another template/controller), which displays additional information for the object clicked.
I'm finding that every time a link is clicked, the factory is retrieving the source data. For something small, it's unnoticeable, but if you're performing an AJAX request to a large dataset, or transforming an XML to JSON, this could take a while. I am uncertain if this is a result of routing, or if it's a poor implementation of what I'm trying to accomplish, but I would like to:
understand why this is happening
retrieve the initial data once and share it between controllers
data.json
[
{"firstName":"John",
"lastName":"Denohn",
"profession":"Student",
"age":10
},
{"firstName":"Mark",
"lastName":"Fatzigio",
"profession":"Doctor",
"age":20
},
{"firstName":"Jennifer",
"lastName":"Cooler",
"profession":null,
"age":30
},
{"firstName":"Kimberly",
"lastName":"Branch",
"profession":"Teacher",
"age":40
}
]
index.html
<!DOCTYPE html>
<html lang="en" data-ng-app="myApp">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href="myApp.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
</head>
<body>
<div data-ng-view="" data-ng-cloak ></div>
<script src="myApp.js"></script>
<script src="myAppModels.js"></script>
<script src="myAppControllers.js"></script>
</body>
</html>
template_initialPageView.html
<div class="page-container" data-ng-cloak>
<!-- Table Content -->
<table class="table" data-ng-cloak>
<thead>
<tr><th colspan="{{keysToShow.length}}"><h1>People</h1></th></tr>
<tr><th data-ng-repeat="header in keysToShow">{{ header.displayName }}</th></tr>
</thead>
<tbody>
<tr data-ng-repeat="person in people | orderBy:orderProp">
<td><a href="#{{[person.firstName, person.lastName].join('_')}}"
data-ng-click="showModal(person)"
>{{ [person.firstName, person.lastName].join(' ') }}</a></td>
<td>{{ person.profession }}</td>
</tr>
</tbody>
</table>
</div>
template_modalContentView.html
<div class="modal-header">
<button type="button" class="close" data-ng-click="cancelModal()">×</button>
<h3 class="modal-title" id="myModalLabel">Person Info</h3>
</div>
<div class="modal-body">
<tabset>
<tab heading="Age">
<h4>Name</h4>
<p>{{ person.firstName + ' ' + person.lastName }}</p>
<h4>Age</h4>
<pre>{{ person.age }}</pre>
</tab>
<tab heading="Profession">
<h4>Name</h4>
<p>{{ person.firstName + ' ' + person.lastName }}</p>
<h4>Profession</h4>
<pre>{{ person.profession }}</pre>
</tab>
</tabset>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-ng-click="closeModal()">Close</button>
</div>
myApp.js
var myApp = angular.module('myApp', ['ui.bootstrap', 'ngRoute']);
/* Routes */
myApp.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'template_initialPageView.html',
controller: 'PageViewController',
controllerAs: 'page'
})
.otherwise({
redirectTo: '/home'
});
});
myAppControllers.js
var myAppControllers = {};
// Define: Page View Controller
myAppControllers.PageViewController = function ($scope, $modal, modelFactory) {
init();
function init(){
$scope.orderProp = '';
$scope.keysToShow = [{'displayName':'Fullname'},{'displayName':'Profession'}];
modelFactory.getPeople().success(function(data){
$scope.people = data;
});
}
$scope.showModal = function(person) {
console.log('person clicked', person);
$scope.person = person;
var modalInstance = $modal.open({
controller: 'ModalController',
controllerAs: 'modal',
templateUrl: 'template_modalContentView.html',
resolve: {
person: function(){
return $scope.person;
}
}
});
};
};
// Define: Modal Controller
myAppControllers.ModalController = function ($scope, $modalInstance, person) {
init();
function init(){
$scope.person = person;
}
$scope.cancelModal = function (){
$modalInstance.dismiss('cancel');
};
$scope.closeModal = function () {
$modalInstance.close();
};
};
// Add controlers to the module
myApp.controller(myAppControllers);
myAppModels.js
myApp.factory('modelFactory', function($http){
var factory = {};
factory.getPeople = function (){
return $http.get('data.json');
};
return factory;
});
You can try this, it initially returns an empty array that will be populated when $http.get() returns and it re-uses the array each time it is called:
myApp.factory('modelFactory', function($http){
var factory = {};
factory.getPeople = function () {
if (typeof(factory.people) == "undefined") {
factory.people = [];
$http.get('data.json').success(function(result) {
var i = 0;
for (i = 0; i < result.length; i++) {
factory.people.push(result[i]);
}
});
}
return factory.people;
};
return factory;
});
And don't forget to change your assignment to accept an array and just use that:
$scope.people = modelFactory.getPeople();
(PLUNKR)

Categories

Resources