How to double bind? - javascript

I`m new to angularJS. I have a table, I make a request and output some default data in my tablerows from Controller2. Now I want to make a different request and output other data in the same table,but this time from Controller1. How can I do this ?
Html
<tr ng-repeat="stats in statsFromTable" ng-show="statsFromTable.length > 0">
<td><span ng-bind="stats.PERS"></span></td>
JavaScript
Controller2 -- > $scope.statsFromTable = data.REQUEST_ATTRIBUTES.historyList; // the first default request
Controller1 -- > ???

Don't use $rootScope to share info between controllers. For that purpouse you can use a service.
So your code could look like:
angular.
module('yourAngularModule', []).
controller('MyController', ['$scope','myService', function ($scope, myService) {
$scope.number1 = myService.number;
}]).
controller('MyController2', ['$scope','myService', function ($scope, myService) {
$scope.number2 = myService.number;
}]).
service('myService', [function() {
var service = {
number:0
};
return service;
}]);
})(window.angular);
And then you could bind the data like:
<div ng-controller="MyController">
<h3>Controller 1</h3>
{{number1}} // Will display service.number --> 0
</div>
<div ng-controller="MyController2">
<h3> Controller 2</h3>
{{number2}} // Will display service.number --> 0
</div>
I did a plnkr where you can take a look at how two different controllers share info via service.

you can use $rootScope to do this. here is the example demo for you i have created

Related

How to get the controller of a form

Say I have several forms each with their own controller that look like this
<div ng-controller="MyController1 as ctrl">
<label>Some label </label>
</div>
<div ng-controller="MyController2 as ctrl">
<label>Some label </label>
</div>
And I have a global controller, that gets the information about the form names. Now I want to find the controllers for each form. For instance, if in my global controller function, I get the name of the first form, how can I find out that its controller is MyController1? Is that even possible?
Calling a controller from another controller is possible. But, I believe the problem you're trying to solve is somewhere else: the architecture of your app.
Ideally, your app should 'react' to changes on the state. The state should be kept in a single place (also called 'single source of truth'), ie. a service. Then you share that service state with as many controllers as you need.
You can either update the service state directly from the controller, or by calling a method on the service itself.
Look at the example below. I hope that sheds some light.
Cheers!
angular.module('app', [])
.service('MyService', function(){
var self = this;
self.state = {
name: 'John'
};
self.changeNameFromService = function() {
self.state.name = 'Peter';
}
})
.controller('Ctrl1', function($scope, MyService){
$scope.state = MyService.state;
$scope.changeName = function(){
// update the state of the scope, which is shared with other controllers by storing the state in a service
$scope.state.name = 'Mary';
}
})
.controller('Ctrl2', function($scope, MyService){
$scope.state = MyService.state;
// call a method defined in service
$scope.changeName = MyService.changeNameFromService;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
Ctrl1: {{state.name}}
<button ng-click="changeName()">Change name!</button>
</div>
<div ng-controller="Ctrl2">
Ctrl2: {{state.name}}
<button ng-click="changeName()">Change name from service!</button>
</div>
</div>

How to pass ng-model to controller

I have a very hierarchical data structure in JSON. I also have a re-usable (Django) template that gets bound to part of that structure. So, I need to know where in that structure I am for any given template. I am almost there:
http://jsfiddle.net/trubliphone/fd64rn3y/
The missing bit is being able to pass the current ng-model to a controller.
Here is some code (but the jsfiddle above shows more detail):
my_app.js:
var myApp = angular.module('myApp', []);
myApp.factory('$global_services', ['$http', function($http) {
var data = {};
$http.get("some_url", {format: "json"}) {
/* THIS REQUEST RETURNS A BIG CHUNK OF HIERARCHICAL JSON */
.success(function (data) {
data = data;
})
});
return {
getPathFromModel: a_clever_fn_i_wrote_that_returns_a_string(),
getModelFromPath: a_clever_fn_i_wrote_that_returns_a_model()
}
}]);
myApp.controller('MyController', ['$scope', '$attrs', '$global_services', function( $scope, $attrs, $global_services ) {
if ($attrs.currentModelPath) {
/* if you passed current_model_path, get the current_model too */
$scope.current_model_path = $attrs.currentModelPath;
$scope.current_model = $global_services.getModelFromPath($scope.current_model_path);
}
else if ($attrs.currentModel) {
/* if you passed current_model, get the current_model_path too */
$scope.current_model = $attrs.currentModel;
$scope.current_model_path = $global_services.getPathFromModel($scope.current_model);
}
}]);
my_template.html:
<div ng-app="myApp">
<div ng-controller="MyController" current_model_path="data">
{{current_model.name}}:
<ul ng-repeat="child in current_model.children">
<input type="text" ng-model="child.name"/> {{ child.name }}
<!-- LOOK: HERE IS A NESTED CONTROLLER -->
<div ng-controller="MyController" current_model="child">
{{current_model.name}}:
<ul ng-repeat="child in current_model.children">
<input type="text" ng-model="child.name"/> {{ child.name }}
</ul>
</div>
</ul>
</div>
</div>
The problem is in the "div" element for the nested controller; I pass the {{child}} ng variable as an attribute, but when the controller recieves it, it just interprets it as the JavaScript string "child". How can I pass the actual model object?
Thanks.
<div ng-controller="MyController" ng-init="data = child">
this will add an object to the inner scope named data.

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

Can't get the datas in angularJs

I have html page like
<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>
And i have angular Js code is
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
{
$http.get('data/userData.json').success (function(data){
$scope.users = data;
$scope.users.doClick = function(user,event) {
userInfo(user);
}
});
}]);
function userInfo(users)
{
console.log(user);
userDirectory.controller("userDetailsControl", function($scope)
{
console.log('well')
$scope.user = users;
console.log($scope.user)
});
}
Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).
I am new one in angular jS. I dont know this logic is correct or not.
I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section
First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.
Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
$scope.selectUser = function(user){
$rootScope.selectedUser = user;
}
$http.get('data/userData.json')
.success (function(data){
$scope.users = data;
});
})
.controller("userDetailsControl", function($scope, $rootScope){
$rootScope.$watch("selectedUser", function(newVal){
$scope.user = newVal;
}
}
and in your HTML:
<div ng-controller="userListControl">
<button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
<div>{{user.name}}</div>
<div>{{user.otherDetails}}</div>
</div>

changing variable value from another controller

I've created an application in angular js. In the application i'm having three controllers. The first controller MainController is in the body tag, within which i have another two controller FileController and TypeController.
Inside the TypeController I've a select box having the model name data.selectedFileTypes which shows several filenames. Now within the FileController controller I've another select box with model name fileproperty.allowsFiles, and having Yes and No values. The first time it get initialized within the FileController controller.
But when i select a different file from the select of the model data.selectedFileTypes how can i change the select value again to No of the model fileproperty.allowsFiles from the ng-change function of the file select
an anyone please tell me some solution for this
html
<body ng-controller="MainController">
:
:
<div ng-controller="TypeController">
<select ng-model="data.selectedFileTypes" ng-options="type.name for type in config.fileTypes ng-change="select()">
</select>
</div>
:
:
<div ng-controller="FileController">
<select ng-model="fileproperty.allowsFiles" ng-options="option.value as option.desc for option in files.options"></select>
</div>
:
:
</body>
script
app.controller('TypeController', function($rootScope, $scope)
{
$scope.select = function()
{
:
:
}
}
app.controller('FileController', function($rootScope, $scope)
{
$scope.fileproperty.allowsFiles = 'No';
}
Try this method.
app.controller('MainController', function($rootScope, $scope)
{
$scope.select = function()
{
:
$rootScope.selectedFiles = $scope.data.selectedFileTypes;
:
}
}
Inside your second controller
app.controller('FileController', function($rootScope, $scope)
{
$scope.$watch('selectedFiles', function () {
$scope.fileproperty.allowsFiles = 'No';
}, true);
}
You could also use $broadcast and $on here to handle this scenario:
app.controller('MainController', function($rootScope, $scope)
{
$scope.select = function()
{
$scope.$broadcast('someevent');
}
}
Inside your second controller
app.controller('FileController', function($rootScope, $scope)
{
$scope.$on('someevent', function () {
$scope.fileproperty.allowsFiles = 'No';
});
}
I think it's better practice to put shared properties into a service, then inject the service in both controllers.
Doesn't seem right to abuse a global namespace such as $rootScope when you don't have to.
Here's an example of a single service being bound to a select in one controller's scope and the same service being used in a second controller's scope to display the value in the service.
Here's a codepen: http://cdpn.io/LeirK and the snippets of code below
Here's the HTML:
<div ng-app="MyApp">
<div ng-controller="MainController">
<select ng-model='fileproperties.allowFiles'>
<option id="No">No</option>
<option id="Yes">Yes</option>
</select>
<div ng-controller="FileController">
{{fileproperties.allowFiles}}
<div>
</div>
</div>
And the Javascript:
var app = angular.module('MyApp',[]);
app.controller('MainController', ['$scope', 'FilePropertiesService', function(scope, fileproperties) {
scope.fileproperties = fileproperties;
}]);
app.controller('FileController', ['$scope', 'FilePropertiesService', function(scope, fileproperties) {
scope.fileproperties = fileproperties
}]);
app.service('FilePropertiesService', function(){
this.allowFiles = 'No';
});

Categories

Resources