Dujndaf Dujndaf - 5 months ago 13
AngularJS Question

View not updating when scope is changed inside a directive

How can I update the scope from a directive? Here's a sample code showing what I want.

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>"
}
});


When the button is clicked the
$scope.message
is changed to bar but the view is not updated.

Answer

You didn't inject $scope into your controller.

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

You are creating two instances of your controller: One here: <div ng-controller="sampleController"> The other one for the directive controller : "sampleController",

Each instance will have a different $scope, so when you call bar() inside the directive, it will update $scope.message in the directive's scope, but not outside of it.

You can omit controller : "sampleController", then you will have only one scope. (Although your directive will only work inside <div ng-controller="sampleController">)