2016-07-05 17 views
0

ディレクティブからスコープを更新するにはどうすればよいですか?ここに私が何を望んでいるかを示すサンプルコードがあります。ボタンをクリックするとディレクティブ内でスコープが変更されたときに更新されないビュー

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? 
      } 
     } 
    }) 
+1

(あなたのディレクティブのみ<div ng-controller="sampleController">内部の作業をしますが)、 '$のscope'は未定義です。 – str

+0

ちょうどあなたのコントローラに '$ scope 'を挿入する –

答えて

2

あなたのコントローラに$scopeを注入しませんでした。

あなたのコントローラの2つのインスタンスを作成している
.controller('sampleController',function($scope) { 
    ... 
} 

: ここにワン:<div ng-controller="sampleController"> ディレクティブcontroller : "sampleController"のために他の1、

各インスタンスは)異なる$スコープを持っているので、あなたがバー(呼び出すときますディレクティブ内では、ディレクティブのスコープ内の$ scope.messageは更新されますが、ディレクティブのスコープ内では更新されません。

controller : "sampleController",を省略すると、スコープは1つだけになります。

+0

申し訳ありませんが、$ scopeをコントローラに追加するのを忘れていました。私は含まれている範囲で質問を編集しました – Dujndaf

+0

申し訳ありませんが、明らかでした。私は答えを更新しました。 – marton

+0

コントローラを省略すると、 "sampleController"は$ scope.messageをbarに更新しません。 – Dujndaf

関連する問題