[英]Angular JS, update $scope from controller in directive
I have the following situation: 我有以下情况:
In my app I have a quiz, I store the score and the current question as $scope.current
, $scope.score
in MainCtrl
, then I have a directive called question where I show the question and the choices like: 在我的应用我有一个测验,我存储得分和当前问题为$scope.current
, $scope.score
在MainCtrl
,然后我有一个指令称为问题,我展示的问题,并像选择:
angular.module('quiz')
.directive('myQuestion', function() {
return {
restrict: 'EA',
replace: true,
scope: {
question: '=',
index: '='
},
link: function(scope) {
scope.validate = function(index) {
var isCorrect = index === scope.question.correct;
if(isCorrect) {
console.log('Correct!');
//$scope.score += 10 ($scope score from MainCtrl)
}
if(!isCorrect) {
console.log('Incorrect!');
scope.correct = false;
}
//$scope.current += 1;
};
templateUrl: 'assets/javascript/tpl/question.html'
};
});
In my html I have the following structure: 在我的html中,我具有以下结构:
<div class="quiz">
<h2>Current Question: {{current}}</h2>
<h2>Your score: {{score}}</h2>
<my-question ng-repeat="q in questions track by $index"
ng-if="isCurrent($index)" //in controller i compare $index with $scope.current
question="q"
index="$index"></my-question>
</div>
My question is, how can I update $scope.score
or $scope.current
from the directive link function? 我的问题是,如何从指令链接函数更新$scope.score
或$scope.current
?
Can someone explain me please the best way? 有人可以最好的方式向我解释吗?
In the case where you have directive and want to update parent controller scope I think it would be best to use model with a dot .
在您有指令并想要更新父控制器作用域的情况下,我认为最好将模型与点一起使用.
For that you need to change model a bit in parent controller 为此,您需要在父控制器中稍微更改模型
$scope.quiz = {
score: 0
current: 0
}
then in directive you can do 然后在指令中你可以做
$scope.quiz.score = 'whatever, really'
$scope.quiz.current = 'current index'
if you refer to a model like that quiz.score
then it will not create score
on current scope but instead it will find parent model quiz
and change the score
如果您引用类似quiz.score
的模型,则它不会在当前范围内创建score
,而是会找到父模型quiz
并更改score
Hope that makes sense 希望有道理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.