AngularJS - 指令双向绑定不与ISOLATED Scope一起使用

时间:2014-08-14 04:34:44

标签: angularjs directive

我正在构建一个演示天气应用程序,使用控制器/提供商& 2个指令,(具有隔离范围,一个指示用于呈现值得预测的周)以及另一个用于在页面顶部显示点击的工作日预测的指令。

点击其中一个工作日,我试图在屏幕顶部显示点击的工作日。 如果我删除指令中的隔离范围,则此方法可以正常工作,但它不适用于隔离范围。

有人可以建议我在这里缺少什么吗?

链接:具有隔离范围的指令:http://plnkr.co/edit/L9AcMv?p=preview这不起作用?我在这里缺少什么?

代码供您参考:

    app.directive('myWeather', function() {
      return {
        restrict: 'EA',
        transclude: 'true',
//If I comment below scope then it works fine though it does not if I am using isolated scope
        scope: {
          place: '=' //Two-way data binding
        },
        templateUrl: 'my-weather.html'
      };
    });

    app.directive('selectedWeather', function() {
      return {
        restrict: 'EA',
        transclude: 'true',
//If I comment below scope then it works fine though it does not if I am using isolated scope
        scope: {
          place: '=' //Two-way data binding
        },
        templateUrl: 'selected-weather.html'
      };
    });

非常感谢,

1 个答案:

答案 0 :(得分:4)

使用隔离范围时,控制器范围的setSelectedItem方法是不可见的。

解决方案:

将setSelectedItem添加到指令isoalted范围。 + 添加双向数据绑定也可以预测。

http://plnkr.co/edit/e5ApIg?p=preview

工作

所做的更改是:

app.directive('myWeather', function() {
  return {
    restrict: 'EA',
    transclude: 'true',
    //If I comment below scope then it works fine though it does not if I am using isolated scope
    scope: {
      place: '=', //Two-way data binding
      /// here added a two way data binding to forecast too
      forecast: '='
    },
    templateUrl: 'my-weather.html',
    /// here added setSelectedItem to isolated scope.
    link: function (scope,e,a) {
      scope.setSelectedItem = function(forecast) {
          scope.forecast = forecast;
      }
    }
  };
});

关于index.html

<div my-weather place="place" forecast="forecast"></div>