在'上传递范围;单击';回调函数angularjs

在'上传递范围;单击';回调函数angularjs,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,HTML: 这是我想编辑的东西 Javascript: <body ng-app="EditApp"> <div ng-controller="MainController"> <h1 click-to-edit>This is something I want to edit</h1> </div> </body> angular.module(“EditApp”,[]) .cont

HTML:


这是我想编辑的东西
Javascript:

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

    </div>
  </body>
angular.module(“EditApp”,[])
.controller(“主控制器”[“$scope”,函数($scope){
$scope.text=“这是我想编辑的内容”;
}])
.指令(“clickToEdit”,函数(){
返回{
限制:“EA”,
模板:“”,
是的,
链接:函数(范围、元素、属性){
scope.showInput=false
元素上(“单击”,函数(){
作用域。$parent.showInput=true
})
} 
}
})
为什么
showInput
没有改变?或者是因为我必须做一个
范围。$apply()
?我是否应该在单击功能中以某种方式传入
范围


谢谢

附加一个
ng单击转换容器上的
,您也不需要在作用域上使用
$parent
。是的,它没有更新,因为

  • 您正在更新错误的范围
  • angular不知道从外部注册的处理程序更新的范围,除非您知道,或者直到下一个摘要周期刷新不会发生:-

    element.on(“单击”,函数()){
    scope.showInput=true
    作用域:$apply();
    });

尝试:-

指令(“clickToEdit”,函数(){
返回{
限制:“EA”,
模板:“”,
是的,
链接:函数(范围、元素、属性){
scope.showInput=false;
scope.showClick=函数(){
scope.showInput=true
}
} 
}
});


是的!这很好用——真不敢相信我没有想到ngclicks@MohamedElMahallawy我建议尽可能采用角度化的方式来注册事件,这样您就不会出现像下面这样的范围同步问题:)
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

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