指令 link 函数 angularjs 中的双向数据绑定不起作用

Two way data binding doesn't work from directive link function angularjs

我正在尝试在指令视图 html.

中使用指令'link: function 中声明的变量

我尝试使用的变量是来自对象的 int,该对象(此对象)声明为名为 slider 的 $scope 变量。

我正在尝试显示它:

<div>
    {{ slider.step }}
</div>

打印值是 aa : 1,它没有改变,尽管它应该改变。它一直是 1,它不想重新绑定 :( 虽然我稍后会在代码中更改此值。看看完整的指令代码。我在几个地方更改它的值:

..in 指令 link 函数..

link: function($scope, el) {
  $scope.slider = {
    step: 1,
    changeSlide: function (step) {
      if(step === 1) {
        this.step = 1;
        console.log('changed step to 1: ' + $scope.slider.step);
      }
      if(step === 2) {
        this.step = 2;
        console.log('changed step to 2: ' + $scope.slider.step);
      }
    }
  }
  $timeout(function () {
    var i = 1;
    $scope.slider.changeSlide(i);
    setInterval(function () {
        i++; if(i === 3) i = 1;
        $scope.slider.changeSlide(i);
    }, 5000);
  });
}

我正在改变 if(step === 2) 的步骤。

基本上垂直滑块可以正常工作。唯一缺少的是我无法从视图访问当前步骤,也无法显示 "which slide is currently selected" 的正确活动点。这就是为什么我需要了解这一步但我做不到。

Here 是 plnkr 演示。

数据更改后必须使用$timeout(function(){ $scope.$apply(); });

工作示例

angular.module('plunker', []);

function MainCtrl($scope) {
  $scope.hello = 'World';
}

angular.module('plunker').directive('elements', function($timeout) {
  return {
    restrict: 'E',
    scope: {
      name: '='
    },
    template: `<div>
    {{ slider }}
</div>`,
    link: function($scope, el) {

      $scope.slider = {
        step: 1,
        changeSlide: function(step) {
          console.log(11, step)
          if (step === 1) {
            this.step = 1;
            console.log('changed step to 1: ' + $scope.slider.step);
          }
          if (step === 2) {
            this.step = 2;
            console.log('changed step to 2: ' + $scope.slider.step);
          }
          $timeout(function(){ $scope.$apply(); });
        }
      }
      var i = 1;

      $timeout(function() {
        $scope.slider.changeSlide(i);
        setInterval(function() {
          i++;
          if (i === 3) i = 1;
          $scope.slider.changeSlide(i);
        }, 5000);
      });
    }
  };
});
<!doctype html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script>
    document.write("<base href=\"" + document.location + "\" />");
  </script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <elements></elements>
</body>

</html>