在'click'回调函数angularjs中传递范围

时间:2014-09-22 19:14:52

标签: angularjs angularjs-directive angularjs-scope

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

      })
    } 
  }
})

为什么showInput没有改变?或者是它,但我必须做scope.$apply()?我应该在点击功能中以某种方式传递scope吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

在翻译容器上附加ng-click,您也不需要在范围内使用$parent。是的,它没有更新,因为

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

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

尝试: -

.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