AngularJS - 指令双向绑定不是孤立的工作范围工作范围、孤立、绑定、双向

2023-09-13 04:03:02 作者:被强煎的蛋

我建立一个演示的天气应用程序,通过使用控制器/供应商和放大器; 2指令,(带隔离范围,一是指令渲染本周值得预测和放大器;另一指令在页面顶部显示点击平日预测)。

I am building a demo weather app, by using controller/provider & 2 directives,( with isolated scope, one directive for rendering week worth forecast & another directive to display clicked weekday forecast on top of the page).

在点击的工作日,我想显示在屏幕上方点击的工作日之一。 此,如果我删除指令隔离范围,但它不到位孤立的工作范围内正常工作。

On click on one of the week days I am trying to show clicked weekday on top of the screen. This works fine if I remove Isolated scope in directives however it does not work with isolated scope in place.

任何人都可以请建议什么,我在这里丢失?

Can anyone please suggest what I am missing here?

链接:具有隔离范围一个指令: http://plnkr.co/edit / L9AcMv?p = preVIEW (这不工作是什么?我在这里丢失?)

Link: A directive with Isolated Scope: http://plnkr.co/edit/L9AcMv?p=preview ( this does not work? What Am I missing here?)

code,供您参考:

    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'
      };
    });

非常感谢,

推荐答案

当您使用隔离范围,控制器范围的setSelectedItem方法是看不见的。

When you use isolated scope, the setSelectedItem method of controller scope are invisible.

解决方案:

一个setSelectedItem添加到该指令isoalted范围。+添加双向数据绑定预测了。

Add a setSelectedItem to the directive isoalted scope. + Add a two way data binding to forecast too.

在工作: 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

And on index.html

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