How to encapsulate $scope in Angular.Js

橙三吉。 提交于 2019-12-13 19:07:35

问题


I have a pattern, which I want to use twice, but with different values. For example:

 .directive("day", function($scope){
     return {
        template: '<div>{{day}}</div>'
        }
    }

Can I use it in two another directive, but encapsulate 'day' to see result like that:

    <div>1</div>
    <div>2</div>

Especially if I want to keep binding value of all 'day'


回答1:


you meant something like this?

app.directive('day', function(){
  return {
    scope: {
      dayValue: '='
    },
    template: '<div>{{dayValue}}</div>'
  }
})

app.directive('outerDirective', function(){
  return {
    link: function($scope){
      $scope.days = [1,2,3];
    },
    template: '<day day-value="day" ng-repeat="day in days"></day>'
  }
})



回答2:


What you want is called an "isolate" scope where you bind an attribute of the directive from the local "isolate" scope to the parent scope.

app.directive('day', function(){
  return {
    scope: {
      day: '='
    },
    template: '<div>{{day}}</div>'
  }
})

HTML

    <div ng-init="day1='Thursday'; day2='Friday'">

        <div day="day1"></div>
        <div day="day2"></div>

    </div>

Result

Thursday

Friday

For more on directive scopes see the AngularJS $compile API Reference -- scope.



来源:https://stackoverflow.com/questions/34693199/how-to-encapsulate-scope-in-angular-js

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