为什么父方范围在直接方面不会改变

时间:2015-07-22 00:07:17

标签: javascript angularjs

我有两条指令。 当我从子范围更改父范围中的数据时,数据不会更改。 您可以通过单击其中一个li元素进行测试。

http://plnkr.co/edit/7ewMokT2vTnLWBFEdm14?p=preview

HTML

    <ez-select>
 <ez-option title="option 1">
        Option 1 inside
        <input ng-model="x">{{x}}
    </ez-option>
  <ez-option title="option 2">
        Option 2 inside
    </ez-option>
</ez-select>

JAVASCRIPT

m.directive('ezSelect',function(){
    return {
      template:'<ul ng-transclude></ul><br>Selected: {{selected}}',
      transclude:true,
      link:function($scope){
        $scope.selected=1
      }
    }
  });
    m.directive('ezOption',function(){
        return {
            template:'<li></li><div ng-show=selected ng-transclude class=body></div>',
            link:function ($scope,iElement,iAttrs,controller,tanscludeFn){
                iElement.find('li').html(iAttrs.title)
                iElement.closest('ez-select').find('.body')
                iElement.find('li').on('click',function(){
                  $scope.selected=false
                  $scope.$parent.selected=2
                })
            },
            controller:function($scope){
              $scope.selected=false
            },
            transclude:true
        }
    })

1 个答案:

答案 0 :(得分:1)

查看此工作演示:http://plnkr.co/edit/lRKhAHB9zmHKKrcdD6nO?p=preview

需要进行两项修改。

首先,正如charlietfl所评论的那样,总是使用一个对象来共享模型。有关详细说明,请查看此优秀文章:Understanding Scopes。在您的示例中,我将<?php echo "Page entered."; $uploadDir = '../../WHEREVER/WHEREVER/'; chmod('uploads/', 0777); $uploadFile = $uploadDir . basename($_FILES['audioFile']['name']); echo '<pre>'; if (move_uploaded_file($_FILES['audioFile']['tmp_name'], $uploadFile)) { echo "Audio file successfully processed\n"; } else { echo "Audio file processing attempt unsuccessful\n"; } echo 'Here is some more debugging info:'; print_r($_FILES); print "</pre>"; ?> 更改为selected

其次,由于data.selected事件超出了Angular生命周期,因此您需要使用$scope.$apply手动触发onClick周期。所以:

$digest

有关编码风格的一些问题:

  • 按照惯例,我们在链接功能
  • 中使用$scope.$apply(function () { $scope.selected=false; $scope.$parent.data.selected=2; }); 代替scope
  • 使用$scope
  • 而不是element.on