2016-07-05 38 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

'$ scope'未定義。 – str

+0

只是在您的控制器中注入'$ scope' –

回答

2

你沒有注入$scope到控制器中。

.controller('sampleController',function($scope) { 
    ... 
} 

你正在創建你的控制器的兩個實例: 一個位置:<div ng-controller="sampleController"> 另一個用於指令controller : "sampleController"

每個實例都將有一個不同的$範圍,所以當你打電話吧()在指令內部,它會在指令的作用域中更新$ scope.message,但不在它之外。

你可以省略controller : "sampleController",那麼你將只有一個範圍。 (雖然你的指令只能在<div ng-controller="sampleController">之內工作)

+0

抱歉,我忘記將$ scope添加到控制器中。我已經用包含的範圍編輯了這個問題 – Dujndaf

+0

對不起,看起來很明顯。我已經更新了答案。 – marton

+0

省略了控制器:「sampleController」仍然不會將$ scope.message更新爲條。 – Dujndaf

相關問題