简体   繁体   English

设置$ scope变量AngularJS

[英]Setting $scope variables AngularJS

So i am having an issue with adding a variable to the $scope after an event. 所以我在事件后将变量添加到$ scope中遇到了问题。 Here is the HTML for the select box. 这是选择框的HTML。 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); 我可以获取要发布到console.log(cName);的变量。 but it won't show up when i have the {{cName}} 但是当我有{{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. 没有更多信息,很难完全调试,但是从我可以看到的角度来看,我建议将整个html包装在控制器ClientCtrl中,否则h2和p标签将无法访问其创建的范围。

<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. 实际上,您不必在ng-change事件中传递名称,因为您实际上已经在范围内使用了该名称。 The changeEvent can the use $scope.name directly instead of passing it as a parameter. changeEvent可以直接使用$ scope.name而不是将其作为参数传递。

ng-change="selectChange()"

js 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;) id建议您给它起一个比名字更好的名字,我想这是在谈论一个人,因此,如果您将其命名为Person.Name等,将更易于阅读;)

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. 由于要为控制器创建作用域,因此您还需要将打印内容包装在与现在具有名称相同的控制器中,以使其起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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