0

HTML:

  <body ng-app="EditApp">
    <div ng-controller="MainController">
    <h1 click-to-edit>This is something I want to edit</h1>

    </div>
  </body>

Javascript:

angular.module("EditApp", [])
.controller("MainController", ['$scope', function($scope){
  $scope.text = "This is something I would like to edit";

}])
.directive("clickToEdit", function(){
  return {
    restrict: 'EA',
    template: " <input type='text' value='{{ text }}' ng-show='showInput'/> <div ng-transclude ng-hide='showInput'></div>",
    transclude: true,
    link: function (scope, element, attrs) {
      scope.showInput = false
      element.on("click", function(){

        scope.$parent.showInput = true

      })
    } 
  }
})

Why is the showInput not changing? Or is it but I have to do a scope.$apply() ? Should I be passing in the scope somehow within the on click function?

Thanks!

0

1 Answer 1

1

Attach an ng-click on the transclusion container, and you don't need to use $parent on scope as well. And yes it is not updating because

  • you are updating wrong scope.
  • angular does not know about the scope being updated from the handler registered externally unless you do, or until next digest cycle refresh will not happen :-

    element.on("click", function(){ scope.showInput = true scope.$apply(); });

Try:-

.directive("clickToEdit", function(){
  return {
    restrict: 'EA',
    template: " <input type='text' value='{{ text }}' ng-show='showInput'/> <div  ng-click='showClick()' ng-transclude ng-hide='showInput'></div>",
    transclude: true,
    link: function (scope, element, attrs) {
      scope.showInput = false;
      scope.showClick = function(){
         scope.showInput = true
      }
    } 
  }
});

Plnkr

Plnkr2 update text on blur

Sign up to request clarification or add additional context in comments.

2 Comments

Yes! That works perfectly - cannot believe I didn't think of ngclicks
@MohamedElMahallawy As much as possibly I would suggest to go with angular way of registering events so you don't end up with scope synchronization issues like these.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.