smith
smith

Reputation: 55

scope property not reflecting in view after click event

I am new to Angular, trying to implement custom directives.

What i am trying to do is to change a property which is on the scope after a click event via link function in custom directive.

while it does show that the scope property is altered in "Developer tools", but not reflecting in view.

View:-

<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="ISO-8859-1">
<title>IndexPage</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="new.js"></script>
</head>
<body ng-controller="mycontroller as c">
<div> data from mycontroller is: {{c.data}}</div>
<div get-data></div>
</body>
</html>

APP:-

var app=angular.module("app",[]);

app.controller("mycontroller",function(){
this.data="france will win the wrld cup";
});
//controller end

app.directive("getData", function($compile){
return{
restrict: "EA",
template: "<div>click me:  </div>",
link:function (scope,elem,attr){
elem.bind("click",function(){
    console.log(scope);
    $compile(scope);
    scope.c.data="croatia will win the world cup";
    console.log(scope.c.data);
}); 

}
};
//object

});

Output after the click event:-

data from mycontroller is: france will win the wrld cup

click me:

Upvotes: 1

Views: 72

Answers (1)

er-sho
er-sho

Reputation: 9771

As you said

while it does show that the scope property is altered in "Developer tools", but not reflecting in view.

Its because your view doesn't know that the value has been changed in controller and it shows you old values you have to notify view that the value has been changed from controller so may use scope.$apply in your directive.

scope.$apply(function () {
      ...
});

Please have a look on below link article and read full page carefully. you will get complete idea about scope.$apply

https://www.sitepoint.com/understanding-angulars-apply-digest/

Upvotes: 1

Related Questions