简体   繁体   中英

Setting $scope variables AngularJS

So i am having an issue with adding a variable to the $scope after an event. Here is the HTML for the select box. Basically when it is changed i need the scope to change.

Index.html

<select ng-controller="ClientCtrl" ng-model="name" 
ng-options="v.name for (k, v) in client" ng-change="selectChange(name)">
</select>

<h2>{{cName}}</h2>
<p>Age: {{cAge}}</p>
<p>Notes: {{cNotes}}</p>

Controller.js

$scope.selectChange = function(name){
    $scope.cName = name.name;
    $scope.cAge = name.age;
    $scope.cNotes = name.notes;
  };

I have tried a few things to get those variable set. Obviously this one above, then this one:

$scope.selectChange = function(name){
        $scope.cName = name.name;
        $scope.cAge = name.age;
        $scope.cNotes = name.notes;
        $scope.$apply();
  };

I still don't quite understand apply but i thought i'd give it a try. Any help would be awesome, just need a pointer to wrap my head around why this wouldnt work.

I can get the variables to post to the console.log(cName); but it won't show up when i have the {{cName}}

Without more info its hard to debug completely, but from what i can see i would recommend wrapping the entire piece of html in the controller ClientCtrl or else the h2 and p tags wont have access to the scope that it creates.

<div ng-controller="ClientCtrl">
  <select ng-model="name" ng-options="v.name for (k, v) in client" ng-change="selectChange(name)">
  </select>

  <h2>{{cName}}</h2>
  <p>Age: {{cAge}}</p>
  <p>Notes: {{cNotes}}</p>
</div>

Hope this helps otherwise post more info or use a plunker...

You actually dont have to pass in the name in the ng-change event, since you actually already have that in the scope. The changeEvent can the use $scope.name directly instead of passing it as a parameter.

ng-change="selectChange()"

js

$scope.selectChange = function(){
    $scope.cName = $scope.name.name;
    and so on.  
};

id suggest you give it a better name than name, i guess were talking about a person, so it would be easier to read if you call it Person.Name and so on;)

You also need to wrap your print within the same controller as you now have name in, to make it work, since the scope gets created for the controller.

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