AngularJS:在$scope公开、控制器定义的模型上调用$scope公开、控制器定义的函数的首选方法
您有一个控制器,一个在其作用域上公开的模型,用户可以在模板中操作该模型,控制器中的一个函数作用于该模型,模板中的单击处理程序将调用该模型。何时以及为什么您更愿意:AngularJS:在$scope公开、控制器定义的模型上调用$scope公开、控制器定义的函数的首选方法,angularjs,Angularjs,您有一个控制器,一个在其作用域上公开的模型,用户可以在模板中操作该模型,控制器中的一个函数作用于该模型,模板中的单击处理程序将调用该模型。何时以及为什么您更愿意: 通过模板将模型作为参数调用函数 在范围内关闭模型的情况下调用函数 编辑:在约翰·林德奎斯特的著作中,他提倡使用第一种形式,声称它使测试更容易。我同意这一点,因为如果传入参数,控制器方法的测试可能更可读 模板: <div ng-app="myApp"> <div class="container demo
- 通过模板将模型作为参数调用函数
- 在范围内关闭模型的情况下调用函数
<div ng-app="myApp">
<div class="container demo-container" ng-controller="MyCtrl">
<label for="model_input">
Model:
<input type="text" class="form-control" ng-model="model" name="model_input"/>
</label>
<p>
Invoke function with <strong>'{{model}}'</strong> explicitly through template
</p>
<button class="btn btn-primary" ng-click="fn_through_tpl(model)">
Click
</button>
<p>
Invoke function with <strong>'{{model}}'</strong> implicitly through controller
</p>
<button class="btn btn-primary" ng-click="fn_through_ctrl()">
Click
</button>
</div>
</div>
在您的示例中,我建议使用后者—您通过控制器调用的函数。使用双向数据绑定,无需传回模型,因为模型已经更新。这对读者来说是多余的和令人困惑的。相反,在控制器上调用作用于模型的行为 我认为前一种模式适用于模型是或包含数组,并且您希望公开作用于数组元素的控制器操作。例如:
<div ng-repeat="comment in post.comments">
{{ comment.message }}
<button ng-click="deleteComment(comment)">Delete comment</button>
</div>
{{comment.message}}
删除评论
这是第一种形式何时合适的一个很好的例子。
<div ng-repeat="comment in post.comments">
{{ comment.message }}
<button ng-click="deleteComment(comment)">Delete comment</button>
</div>