<section ng-app="app" ng-controller="ctrl">
<p ng-show="check && form.$invalid"></p>
<form name="form" ng-submit="init()">
<input type="text" ng-model="text" required/>
<!-- <input type="submit" ng-click="alterCheck()"/> -->
<input type="submit" ng-click="check=true"/>
</form>
</section>
angular.module('app', [])
.controller('ctrl', function($scope){
$scope.check = false;
$scope.init2 = function() {
$scope.text = '';
}
$scope.init = function() {
$scope.init2();
$scope.check = false;
}
$scope.alterCheck = function() {
$scope.check = true;
}
})
在实际项目中,使用 ng-click="check=true"
的方法会造成点击后 p
处于显示的状态,而 ng-click="alterCheck()"
则不会,请问这是什么原因呢?
上述代码无法复现我所说的现象。有什么额外的原因可能造成这一现象吗?
我想大声告诉你2017-05-15 17:05:45
I can reproduce a problem similar to what you described in this example (because I have encountered it before, so I looked at it a few more times):
<p ng-controller="DemoCtrl">
<ul>
<li ng-repeat="item in items">
<input type="radio" name="group" ng-model="item.checked" ng-click="checkIndex = $index">{{ item.name }}
<!-- <input type="radio" name="group" ng-model="item.checked" ng-click="changeCheckIndex($index)">{{ item.name }} -->
</li>
</ul>
checkIndex: {{ checkIndex }}
</p>
var demo = angular.module('myApp', []);
demo.controller('DemoCtrl', function($scope, $timeout){
$scope.checkIndex = 0;
$scope.changeCheckIndex = function(index){
$scope.checkIndex = index;
};
$scope.items = [{
name: 'Beijing',
checked: false
},{
name: 'Shanghai',
checked: false
},{
name: 'Taiyuan',
checked: false
}];
});
This is a very simple demo, passed
ng-repeat
显示一组单选框,通过点击点选按钮,在下面的checkIndex: {{ checkIndex }}
中显示选中的单选框的$index
. See the online demo here: jsfiddle
If you run the current code, you will find that {{ checkIndex }}
There is no change at all. No matter how hard you try, it will be useless to poke the mouse
But if template
is replaced with the part of code I commented out, and the changeCheckIndex
method is used instead, template
换成我注释掉的那部分代码,改用changeCheckIndex
方法,{{ checkIndex }}
it will change.
Then the question is, how did this situation occur? We still have to go back to the documentation (I recently discovered that ng
’s documentation is pretty good):
I think the reason lies in the one defined in
checkIndex = $index
的写法,使得checkIndex
是一个在每个template instance中独立$scope
下的变量,并不是我们在Controller
.
Document address: ngRepeat
PHP中文网2017-05-15 17:05:45
The difference between value copying and object reference is difficult to answer. I can’t reproduce the error, so I can only give a rough idea.