如何從指令更新作用域?這是一個示例代碼,顯示我想要的。 。在指令中作用域更改時視圖不會更新
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?
}
}
})
'$ scope'未定義。 – str
只是在您的控制器中注入'$ scope' –