AngularJS - Directive two way binding not working with ISOLATED Scope

给你一囗甜甜゛ 提交于 2019-12-08 04:05:39

问题


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?

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

Code for your reference:

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

Many Thanks,


回答1:


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

Solution:

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

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

The changes made are:

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

And on index.html

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


来源:https://stackoverflow.com/questions/25300163/angularjs-directive-two-way-binding-not-working-with-isolated-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!