简体   繁体   中英

Angularjs how to change $rootScope variables from UI

I'm making a dynamic web page with angular, the content from the main page should change, but to avoid writing too much code i decided to make it generic, but to know what type of content is being requested i need to send this parameter from a link/button with a ng-click, this would'nt be a problem but when i have to change the controllers i can't read the parameter.

ng-click="name='Name change'"

Here i'm trying to change a $rootScope variable named name, i tried

ng-click="$rootScope.name='Name change'"

even with a service function, but looks like doesn't work (i don't know too much about angularjs so i tried )

 ng-click="$service.cambiarTipo='Name change'"

i made a plunker http://plnkr.co/edit/1BN76SbUAHuOSHs02gpL?p=preview

If you check the console log, you will see that the variable it's undefined, obviously if i change $rootScope.name from a controller i can see it from the other controller, but that's not useful since i need that feed from the user not the controller.

How i can change a rootScope variable from html?

You really shouldn't be using $rootScope all that much, let alone modifying it from the template. With that said, you can assign $rootScope to a $scope variable and access from the template like normal scoped variable. plunker

Controller: $scope.rs = $rootScope

Template: rs.name = 'Name Change'

I would like to reiterate that this is not something you should be doing as it goes against the angular way.

Here'a one using a shared service between the two controller without using $rootscope at all. http://plnkr.co/edit/maKNHgVH20GxTJeCEveh

Note that ng-click is calling the service function. I'm assuming the function is for changing the name.

ng-click="service.cambiarTipo('Name change')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM