Dujndaf Dujndaf - 1 year ago 44
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.


<div ng-controller="sampleController">


var app = angular.module('sample')
$scope.message = "Foo";
$scope.bar = function(){
$scope.message = "Bar";

return {
controller : "sampleController",
restrict : "E",
template : "<button type='button' ng-click='bar()'></button>"

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

Answer Source

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