[英]Angular JS, update $scope from controller in directive
我有以下情况:
在我的应用我有一个测验,我存储得分和当前问题为$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'
};
});
在我的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>
我的问题是,如何从指令链接函数更新$scope.score
或$scope.current
?
有人可以最好的方式向我解释吗?
在您有指令并想要更新父控制器作用域的情况下,我认为最好将模型与点一起使用.
为此,您需要在父控制器中稍微更改模型
$scope.quiz = {
score: 0
current: 0
}
然后在指令中你可以做
$scope.quiz.score = 'whatever, really'
$scope.quiz.current = 'current index'
如果您引用类似quiz.score
的模型,则它不会在当前范围内创建score
,而是会找到父模型quiz
并更改score
希望有道理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.