Use ng-model in nested Angularjs controller

孤街醉人 提交于 2019-12-11 12:54:39

问题


I have two nested controller in angularjs, and want to use ng-model from outer in inner controller. Suppose this

<div ng-controller='outController'>
    // data.Name : from outer controller
    <div ng-controller='innerController'>
         <input type="text" ng-model='name' ng-init='name=data.Name'>
         {{data.Name}} // display this scope value
    </div>
 </div> 

data.Name value display in html page but not bind to name ng-model. How to bind this value to inner ng-model?


回答1:


You should follow dot rule in this case, so that will allow you to access the parent scope inside the child scope using prototypal inheritance. For using this approach you need to have an object declared in your parent controller like here it should be declared in outController then the inner controller will not create a new one, it will use the existing one using prototypal inheritance

Markup

<div ng-controller='outController'>
    // data.Name : from outer controller
  <div ng-controller='innerController'>
        <input type="text" ng-model='data.Name'>
  </div>
</div>

Code

app.controller('outController', function($scope){
   $scope.data = {};

   //..other code here ..//

})


来源:https://stackoverflow.com/questions/32034518/use-ng-model-in-nested-angularjs-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!