![](/img/trans.png)
[英]Why does this.$refs.inuputField'.focus() not work in Vue?
[英]Using this. in angular does not work?
我使用angularjs创建了一个简单的按钮。 因此,视图中HTML中的代码如下所示:
<div ng-controller="ButtonCtrl">
<button ng-click="ButtonCtrl.setIndex(1)">Create another bidding query</button>
<button ng-click="ButtonCtrl.setIndex(2)">Create another asking query</button>
<form ng-hide="ButtonCtrl.isSelected(1)">
<h4>Filling The Bidding Form</h4>
<fieldset class="form-group">
<textarea class="form-control" ></textarea>
</fieldset>
</form>
<div>
并且ButtonCtrl在controller.js中定义如下
app.controller('ButtonCtrl', function($scope) {
this.index=0;
this.setIndex=function(setbutt){
this.index=setbutt;
};
this.isSelected=function(checkbutt){
return this.index===checkbutt;
};
});
但是,我没有得到预期的行为。 当我单击创建另一个出价查询按钮时,表单不会隐藏自身。 当我使用$ scope函数替换变量,例如$ scope.index = 0;时,程序运行。
我不认为问题出在使用this.index,因为它对我的其他程序很有效。 那么,确切的问题是什么?
为了做到这一点,您将必须使用controllerAs语法在html中使用控制器。
<div ng-controller="ButtonCtrl as buttonCtrl">
<button ng-click="buttonCtrl.setIndex(1)">Create another bidding query</button>
<button ng-click="buttonCtrl.setIndex(2)">Create another asking query</button>
<form ng-hide="buttonCtrl.isSelected(1)">
<h4>Filling The Bidding Form</h4>
<fieldset class="form-group">
<textarea class="form-control" ></textarea>
</fieldset>
</form>
<div>
现在,如果在控制器中使用它而不是$ scope,一切都会正常。 看到这里的例子
但是我个人更喜欢在控制器内部使用$ scope。 对我来说,这很自然,但这只是个人选择。
如果你希望能够使用你的语法ButtonCtrl.setIndex(1)
你必须分配this
到$scope
在控制器也喜欢在这里的最后一行:
app.controller('ButtonCtrl', function($scope) {
this.index=0;
this.setIndex=function(setbutt){
this.index=setbutt;
};
this.isSelected=function(checkbutt){
return this.index===checkbutt;
};
// set ButtonCtrl to the $scope
$scope.ButtonCtrl = this;
});
这是一个很好的egghead.io视频,解释了它: 控制器的替代方法 。
但是正如其他答案已经指出的那样。 这并不是AngularJS的惯用用法。
假设您只是想让示例代码正常工作,我注意到了一些事情。 首先, 大多数 Angular代码使用$scope
代替它,以便您可以利用Angular提供的范围功能。 实际上,应该使用$scope
代替 this
。 因此,就遵循Angular方式而言,控制器将如下所示:
app.controller('ButtonCtrl', function($scope) {
$scope.index=0;
$scope.setIndex=function(setbutt){
$scope.index=setbutt;
};
$scope.isSelected=function(checkbutt){
return $scope.index===checkbutt;
};
});
此外,一旦在标记中声明了一个控制器,就不需要为每个方法调用加上前缀。 这是正确使用$scope
的好处之一。 因此,标记将变为如下所示:
<div ng-controller="ButtonCtrl">
<button ng-click="setIndex(1)">Create another bidding query</button>
<button ng-click="setIndex(2)">Create another asking query</button>
<form ng-hide="isSelected(1)">
<h4>Filling The Bidding Form</h4>
<fieldset class="form-group">
<textarea class="form-control" ></textarea>
</fieldset>
</form>
<div>
希望这可以帮助。
您应该在范围内使用$scope
或仅使用变量,而不要使用this
。
像这样:
$scope.index = 0;
$scope.setIndex = function(i) {
$scope.index = i;
};
$scope.isSelected = function(i) {
return ($scope.index === i);
};
(或者例如, var index = 0;
相反,如果由于某种原因您不希望它在范围内)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.