从AngularJS外部访问Controller对象

时间:2016-03-22 08:54:10

标签: angularjs

如果我们使用以下语法声明控制器:

<div ng-app="scopeExample" ng-controller="MyController as ctrl">
    <input id="box" ng-model="ctrl.num"> equals {{ ctrl.num }}   
</div>

<script> 
angular.module('scopeExample', [])
.controller('MyController', [function () {
     this.num=12;
}]);
</script>   

通过以下方式轻松访问控制器对象

var x=angular.element('#box').scope().ctrl

如果我们使用以下语法:

<div ng-app="scopeExample" ng-controller="MyController">
     <input id="box" ng-model="number"> equals {{ number }}   
</div>

angular.module('scopeExample', []).
controller('MyController', ['$scope', function MyController($scope) {$scope.number=124;
  this.num = 369;}]);

我们如何从AngularJS外部访问Controller对象? 在AngularJS内部,更具体地说是在.controller方法内部,可以通过这个。换句话说,我们在哪里找到 num 属性?

1 个答案:

答案 0 :(得分:0)

我担心你无法从你的范围中获得控制器。最好使用here

所述的controller as语法

还要注意那里写的是什么

  

controllerAs语法使用这个绑定到$ scope

的内部控制器

这意味着,否则它不受$ scope限制。