AngularJS : Modifiy scope from antoher controller - angularjs

I'm starting using Angular JS to build a mobile application with Ionic.
I'm trying a thing very simple but it does not work.
HTML
<div ng-controller="MyCtrl">
Hello, {{name}}!
</div>
<div ng-controller="MyCtrl2">
Hello, {{name}}!
</div>
<button ng-controller="MyCtrl" ng-click="MyCtrl.test()">click</button>
JS
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Name 1';
$scope.test = function () {
$scope.name = 'Name on click !';
}
}
function MyCtrl2($scope) {
$scope.name = 'Name 2';
}
I have a similar structure in my Ionic App.
I need to modify the "$scope.name" from another template.
Thanks for help.
JSFiddle : http://jsfiddle.net/ADukg/6649/

This Fiddle will provide you with a working copy of your code.
<div ng-controller="MyCtrl">
<div>
Hello, {{name}}!
</div>
<div ng-controller="MyCtrl2">
Hello, {{name}}!
</div>
<button ng-click="test()">click</button>
</div>
(function() {
function MyCtrl($scope) {
$scope.name = 'Name 1';
$scope.test = function() {
$scope.name = 'Name on click !';
};
}
function MyCtrl2($scope) {
$scope.name = 'Name 2';
}
angular.module('myApp', [])
.controller('MyCtrl', MyCtrl)
.controller('MyCtrl2', MyCtrl2);
})();
You missed the following:
Assigning your controllers to your module
Wrapping the required template html in your ng-controller instead of
declaring it twice.

To modify scope from another controller you need to use either
$rootScope or angular js sevice .
Here is the $rootScope example:
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})

Related

angular js alert by click donot work

i am new to AngularJS so please forgive me this dump question.
i have error
Cannot set property 'test' of undefined
angularjs
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [
function($scope) {
$scope.test = function() {
alert("12312");
}
}
]);
html
<body ng-app="StartModule">
<div ng-controller="ModalDemoCtrl">
<div ng-click="test()">11111</div>
</div>
<body>
You just miss $scope to controller's second argument:
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [ $scope, function($scope) {
$scope.test = function() {
alert("12312");
}
}]);
You're missing the $scope dependency, you need to inject it in your controller :
App.controller('ModalDemoCtrl', ['$scope'
function($scope) {
That's why the $scope variable is undefined, you're not actually injecting any dependency in it.
This uses the Inline Array Annotation: https://docs.angularjs.org/guide/di

Angular Expression is shared while sharing in addthis not expression value

Here is my angular controller:
var myApp = angular.module('myApp', []);
myApp.controller('GreetingController', ['$scope', '$sce', function ($scope, $sce) {
$scope.greeting = 'my test goes here';
$scope.url = "http://google.com";
var shartthis = "<div addthis-toolbox class='addthis_toolbox addthis_default_style addthis_32x32_style' addthis:url='{{url}}' ng-attr-addthis:title='{{greeting}}'><a class='addthis_button_facebook'></a><a class='addthis_button_twitter'></a> <a class='addthis_button_google_plusone_share'></a><a class='addthis_button_compact'></a><a class='addthis_counter addthis_bubble_style'></a> <script type='text/javascript'>var addthis_config = {'data_track_clickback': false, 'data_track_addressbar': false ,};</script></div>";
$scope.shartthishtml = $sce.trustAsHtml(shartthis);
} ]);
and this is my HTML page :
<body ng-controller="GreetingController" ng-model="greeting">
<div ng-model="greeting">
{{greeting}}
</div>
<div ng-bind-html="shartthishtml"></div>
Sharethis button is displaying but when share something it display Angular syntax not its value.
no any console error
myApp.controller('GreetingController', ['$scope', '$sce', function ($scope, $sce) {
$scope.greeting = 'my test goes here';
$scope.url = "http://google.com";
var shartthis = "<div addthis-toolbox class='addthis_toolbox addthis_default_style addthis_32x32_style' addthis:url='{{url}}' ng-attr-addthis:title='{{greeting}}'><a class='addthis_button_facebook'></a><a class='addthis_button_twitter'></a> <a class='addthis_button_google_plusone_share'></a><a class='addthis_button_compact'></a><a class='addthis_counter addthis_bubble_style'></a> <script type='text/javascript'>var addthis_config = {'data_track_clickback': false, 'data_track_addressbar': false ,};</script></div>";
$scope.shartthishtml = $sce.trustAsHtml(shartthis);
} ]);
<body ng-controller="GreetingController">
<div>{{greeting}}</div>
<div ng-bind-html="shartthishtml"></div>
</body>

How to change a value of a "Value" service?

I created an injectable value used in the entire application. Recently, I want to change it value. Here is the simulation of my situation:
angular.module('app', ['ngRoute']) // Create a value
.value('myValue','foo');
angular.module('app')
.controller('firstCtrl', ['$scope', '$filter', 'myValue', function($scope, $filter, myValue){
myValue = 'bar';
console.log(myValue); // bar
}])
.controller('secondCtrl', ['myValue', function(myValue){
console.log(myValue); // foo
}]);
However, the value of myValue didn't change at all, as you can see in the secondCtrl. How can I change this value? Any suggestion would be appreciated.
Google 'angular dot rule', and you've got twice defined app module.
Please see demo below.
var app = angular.module('app', []);
angular.module('app') // Create a value
.value('myValue', {
data: 0
});
app.controller('homeCtrl', function($scope, myValue) {
$scope.value = myValue;
$scope.update = function() {
myValue.data = 8;
}
});
app.controller('secondCtrl', function($scope, myValue) {
$scope.value = myValue;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller="homeCtrl">
<button ng-click="update()">update</button>
<br/>home: {{value.data}}
</div>
<hr/>
<div ng-controller="secondCtrl">
second: {{value.data}}
</div>
</div>
</body>

How to communicate between controllers of two different modules in AngularJs

I want to know that can we communicate between two different controllers in AngularJS. Suppose I have Two modules,
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=preview
1. var app = angular.module('fistModule', []);
app.controller('first', function ($scope) {
$scope.firstMethod= function () {
//my code}
} )
2. var newapp = angular.module('secondModule,[]');
newapp.controller('second', function ($scope) {
$scope.secondMethod= function () {
//my code}
Is there way to communicate between controllers of two different modules.
My Code:
JS:
angular.module('myApp', [])
.controller('ParentCtrl', ['$scope',
function($scope) {
$scope.message = "Child updated from parent controller";
$scope.clickFunction = function() {
$scope.$broadcast('update_parent_controller', $scope.message);
};
}
]);
angular.module('myNewApp', [])
.controller('ChildCtrl', ['$scope',
function($scope) {
$scope.message = "Some text in child controller";
$scope.$on("update_parent_controller", function(event, message) {
$scope.message = message;
});
}
])
HTML:
<div ng-app="myApp" ng-controller="ParentCtrl">
<div ng-app="myNewApp" ng-controller="ChildCtrl">
<p>{{message}}</p>
</div>
<button ng-click="clickFunction()">Click</button>
</div>
As #JB Nizet says, you do it the exact same way. You use a service to communicate between two controllers.
One module needs to have the other module as a dependency. This is always a one-way dependency. I have made secondModule a dependency of firstModule.
As well, the value in the service is stored in an object called data. This is because JavaScript does not pass values by reference -- but does pass objects by reference. So this is a form of boxing.
angular.module('firstModule', ['secondModule'])
.controller('FirstController', FirstController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default value'
}
}
angular.module('secondModule', [])
.controller('SecondController', SecondController);
SecondController.$inject = ['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="firstModule">
<div ng-controller="FirstController as vm">
First Controller in module firstModule<br>
<input type=text ng-model="vm.data.value" />
</div>
<div ng-controller="SecondController as vm">
Second Controller in module secondModule<br>
{{vm.data.value}}
</div>
</div>
your plunker has a very minor issue.
change this
angular.module('myApp', [])
to
angular.module('myApp', ['myNewApp'])

How to resolve main controller first then its child controller

I have a controller as main controller and a its child controller. I want to execute first the main controller and then after its child controller.
I am collecting some userdata and want to keep it in $rootScope so that i could access it within the whole application.
How could i do this ?
<body ng-app="angularApp">
<div ng-controller="MainAppController">
<div ng-controller="childController">
Here i want to access data from "MainAppController" stored in $rootScope
But problem is "childController" runs before "MainAppController"
</div>
</div>
</body>
Here is the angular code
angular.module('MyApp').controller('MainAppController', function($rootScope, service){
$rootScope.userData = [];
service.getUserData().success(function(userDetails){
$rootScope.userData = userDetails;
});
});
angular.module('MyApp').controller('childController', function($scope, $rootScope){
$scope.userInfo = $rootScope.userData;
//Here $scope.userInfo is null because $rootScope.userData gets assigned to $scope.userInfo in this controller before userDetails gets assigned to $rootScope.userData in MainAppController controller.
I want that untill "$rootScope.userData = userDetails;" is not finished , "$scope.userInfo = $rootScope.userData;" must not run.
How can i do this ?
});
There are two ways i know you can do this.
1 way ::
Use $rootScope.userData directly in html and when your parent controller will run $rootScope.userData will get updated and by dual binding feature of angular, your view will get updated accordingly
Code::
//angularjs Code
var app = angular.module('MyApp', []);
app.controller('MainController', function($rootScope, $timeout) {
$rootScope.userData = {};
$timeout(function() {
$rootScope.userData = {name:'myName'};
}, 3000);
});
app.controller('childController', function() {
});
//html code
<div ng-app="MyApp" ng-controller="MainController">
<div ng-controller="childController">
{{userData.name}}
</div>
</div>
2 way::
You can attach $watch on $rootScope.userData in childController so when $rootScope.userData will get updated $watch will run and inside $watch you can update your $scope variable
Code::
//Angularjs Code
var app = angular.module('MyApp', []);
app.controller('MainController', function($rootScope, $timeout) {
$rootScope.userData = {};
$timeout(function() {
$rootScope.userData = {name:'myName'};
}, 2000);
});
app.controller('childController', function($scope, $rootScope) {
$scope.$watch(function(){
return $rootScope.userData;
}, function(){
$scope.userInfo = $rootScope.userData;
});
});
//HTML Code
<div ng-app="MyApp" ng-controller="MainController">
<div ng-controller="childController">
{{userInfo.name}}
</div>
</div>

Resources