ディレクティブからスコープを更新するにはどうすればよいですか?ここに私が何を望んでいるかを示すサンプルコードがあります。ボタンをクリックするとディレクティブ内でスコープが変更されたときに更新されないビュー
HTML
<div ng-controller="sampleController">
<sample-directive></sample-directive>
{{message}}
</div>
jsが
var app = angular.module('sample')
.controller('sampleController',function($scope){
$scope.message = "Foo";
$scope.bar = function(){
$scope.message = "Bar";
}
}).directive("sampleDirective",function(){
return {
controller : "sampleController",
restrict : "E",
template : "<button type='button' ng-click='bar()'></button>"
}
});
$scope.message
はバーに変更されますが、ビューは更新されません(答え)
ここでは別のシナリオです:。
html
<div ng-controller="sampleController as sc">
<sample-directive message="bar"></sample-directive>
{{sc.message}}
</div>
JS
var app = angular.module('sample')
.controller('sampleController',function(){
var sc = this;
sc.message = "foo";
sc.bar = function(){
//change the sc.message to value that is passed to the message attribute in the sample directive
}
}).directive("sampleDirective",function(){
return {
restrict : "E",
template : "<button type='button' ng-click='sc.bar()'></button>",
scope : {
message : "@" //how can I pass this to the sc.message scope?
}
}
})
(あなたのディレクティブのみ
<div ng-controller="sampleController">
内部の作業をしますが)、 '$のscope'は未定義です。 – strちょうどあなたのコントローラに '$ scope 'を挿入する –