相关疑难解决方法(0)

AngularJS控制器中的'this'与$ scope

AngularJS主页"创建组件"部分中,有以下示例:

controller: function($scope, $element) {
  var panes = $scope.panes = [];
  $scope.select = function(pane) {
    angular.forEach(panes, function(pane) {
      pane.selected = false;
    });
    pane.selected = true;
  }
  this.addPane = function(pane) {
    if (panes.length == 0) $scope.select(pane);
    panes.push(pane);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意如何select添加方法$scope,但是addPane添加了方法this.如果我将其更改为$scope.addPane,则代码会中断.

文档说实际上存在差异,但没有提到差异是什么:

以前版本的Angular(pre 1.0 RC)允许您this与该$scope方法互换使用,但现在不再是这种情况了.内的方法上的范围限定this并且$scope是可互换的(角套this$scope),但是不另外你的控制器构造内部.

如何this$scope在AngularJS控制器的工作?

this angularjs angularjs-scope

1013
推荐指数
5
解决办法
29万
查看次数

我应该使用`this`还是`$ scope`?

有两种模式用于访问控制器功能: this$scope.

我应该在何时使用?我理解this是设置为控制器,并且$scope是视图范围链中的对象.但是使用新的"Controller as Var"语法,您可以轻松使用它们.所以我要问的是什么是最好的,未来的方向是什么?

例:

  1. 运用 this

    function UserCtrl() {
      this.bye = function() { alert('....'); };
    }
    
    Run Code Online (Sandbox Code Playgroud)
    <body ng-controller='UserCtrl as uCtrl'>
      <button ng-click='uCtrl.bye()'>bye</button>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 运用 $scope

    function UserCtrl($scope) {
        $scope.bye = function () { alert('....'); };
    }
    
    Run Code Online (Sandbox Code Playgroud)
    <body ng-controller='UserCtrl'>
        <button ng-click='bye()'>bye</button>
    
    Run Code Online (Sandbox Code Playgroud)

我个人发现,this.name与其他Javascript OO模式相比,它更容易上手,更自然.

建议好吗?

angularjs

251
推荐指数
5
解决办法
8万
查看次数

angularjs 中的 $ctrl 是什么?何时在视图中使用 $ctrl 和 $scope?

在示例$ctrl中用于视图

<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list" 
             hero="hero" 
             on-delete="$ctrl.deleteHero(hero)" 
             on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>
Run Code Online (Sandbox Code Playgroud)

何时使用$ctrl以及何时$scope用于与视图交互?

https://docs.angularjs.org/guide/component

angularjs

3
推荐指数
1
解决办法
5566
查看次数

标签 统计

angularjs ×3

angularjs-scope ×1

this ×1