How to get list of values which are selected in ra

2019-02-20 13:22发布

问题:

Here is the HTML, this file is partial where global controller is defined in home page:message object contains data which is loaded from first page .

<ng-repeat data in message>
<input type="radio"  ng-model="accountValue"  value="{{data}}" name="select" />

{{data.Type}}
{{data.Number}}

Continue

JS:

myApp.controller('myCtrl',['$scope',function ($scope) {
    $scope.selectAccount = function(id) {
        alert(id);
    }
}]);

I am getting id as undefined . Please help. thanks

回答1:

So as per the comments what you exactly need is to share the data between two controllers (i.e Global and myCtrl ) on onclick of continue button. There are various ways in which you can do the same.

Build the service which maintain your shared object and the controllers just handle with the reference.Please note in this case it will work untill you will not refresh your page manually as per the ideal circumstances. If your data is not more heavy and you require to maintain it across all pages than in this case you can store it in localstorage.

Here is the demo http://plnkr.co/edit/rrFTmtnYjYNjyE8twUif

You can do the same things by using service & $scope.$watch method. I prefer you do not use $watch for this.Instead of assigning and watching entire service you should just needs to use setter/getter to access and share data.

Here is the demo http://plnkr.co/edit/N2qIMRyDj2SX2BdBleU4

Yep you can also use the $parent property of the scope using ng-model. There are certainly several ways in which you can do the same things: Let's say your HTML is like below

<div ng-controller="ParentCtrl">
   <div ng-controller="ChildCtrl"></div>
</div>

Then you can access your parent scope like this

function ParentCtrl($scope) {
$scope.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl($scope) {
  $scope.parentcities = $scope.$parent.cities;
}

Actually since you defined cities in the parent controller your child controller will inherit all scope variables. So theoritically you don't have to call $parent. The above example can also be written as follows:

function ParentCtrl($scope) {
$scope.cities = ["NY","Amsterdam","Barcelona"];
}
function ChildCtrl($scope) {
$scope.parentCities = $scope.cities;
}

The Angular Docs are using this approach.