Scope value is not getting updated even though the rootscope has the value

219 views Asked by At

I have view

<div ng-controller="DisplayController">
    <display-view style="width:{{model.width}}" value={{model.value}}</display-view>
</div>

Given my controller as

angularModule.controller("DisplayController",function($scope,$rootScope){
    $rootScope.model = DisplayModel;
    this.setInputValue = function(value){
        console.log($rootScope.model);
        $rootScope.model.value =  value;
        console.log($rootScope.model);
        $scope.model.value = $rootScope.model.value;
        $scope.$apply();
    }
});

Model as

var DisplayModel = {
    width:'193px',
    height:'25px',
    value:''
}

on some element click I'm calling the setInputValue function:

element.bind('click', function(event){
    console.log(event + '..event..');
    DispController.setInputValue(event.target.value);
});

display-view is

angularModule.directive('displayView',function(){

return {
    restrict: 'E',
    controller : "DisplayController",
    template: '<input type="text" style={{widthValue}} value={{value}}>',
    link:function(scope,element,attrs){
       scope.widthValue = attrs.style;
       scope.value = attrs.value;
    }
}

})

where the value in $rootScope is not getting updated to the view. How to resolve this issue.

1

There are 1 answers

0
bvakiti On

Here we will have to include replace:true. This will append the value and style to the input element in the display-view directive.

angularModule.directive('displayView',function(){
  return {
  restrict: 'E',
  replace:true,
  template: '<input type="text">'
}
})

Other way to display is by isolating the scope

angularModule.directive('displayView',function(){
return {
restrict: 'E',
scope:{
widthValue: "@",
value : "@"
},
template: '<input type="text" style={{widthValue}} value={{value}}>',
link:function(scope,element,attrs){

}
}
})