AngularJS从指令更新控制器的范围

时间:2014-03-12 16:13:30

标签: angularjs angularjs-directive

鉴于此指令:

writing.directive('writingFocus', function($timeout){
  return {
    restrict: 'AC',
    scope: false,
    link: function(scope, element, attrs){
      scope.$watch(attrs.writingFocus, function(value){
        console.log('Value from directive', value);
        if(value === true){
          $timeout(function(){
            element[0].focus();
            scope[attrs.writingFocus] = false; // Not in controller's scope!!!
          });
        }
      });
    }
  }
});

以这种方式使用:

<input type="text" ng-model="selectedNote.title" writing-focus="justOpened">

指令中对justOpened(attrs.writingFocus)所做的更改未应用于我正在观看它的控制器范围内:

$scope.$watch('justOpened', function(val, old){console.log('value from controller', val, old)})

即使使用具有双向绑定的隔离范围也不起作用:

writing.directive('writingFocus', function($timeout){
  return {
    restrict: 'AC',
    scope: {
        writingFocus: '='
    },
    link: function(scope, element, attrs){
      scope.$watch('writingFocus', function(value){
        console.log('Value from directive', value);
        if(value === true){
          $timeout(function(){
            element[0].focus();
            scope.writingFocus = false; // Not in controller's scope!!!
          });
        }
      });
    }
  }
});

它第一次运行,从控制器获取值,但看起来没有绑定。

控制器:

writing.controller('NotesCtrl', function($scope){
  $scope.notes = db.findAll();
  $scope.$watch('justOpened', function(val, old){console.log('value from controller', val, old)})

  $scope.add = function(){
    var note = {title: 'new note'};
    note.id = db.insert(note);
    $scope.notes.unshift(note);
    $scope.open(note);
  }

  $scope.open = function(note){
    $scope.selectedNote = note;
    $scope.justOpened = true;
  }    

  $scope.open($scope.notes[0]);
});

更新

问题是该指令是在两个创建新范围的ngIf下应用的......

2 个答案:

答案 0 :(得分:0)

尝试在函数

之外移动selectedNote和justOpened声明
 $scope.open = function(note){
    $scope.selectedNote = note;
    $scope.justOpened = true;
  }  

答案 1 :(得分:0)

之所以发生这种情况,是因为该指令属于两个ngIf指令,它们创建了新的范围。

解决:

<input type="text" ng-model="selectedNote.title" writing-focus="$parent.$parent.justOpened">

writing.directive('writingFocus', function($timeout, $parse){
  return {
    restrict: 'AC',
    scope: false,
    link: function(scope, element, attrs){
      var model = $parse(attrs.writingFocus);
      scope.$watch(model, function(value){
        if(value === true){
          $timeout(function(){
            element[0].focus();
            model.assign(scope, false);
          });
        }
      });
    }
  }
});