Angular指令:将多个值从指令传递到作用域

3
我希望能够从指令的多个属性中向$scope暴露多个值。 这些指令是动态生成的,看起来像这个例子:
<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>

我需要$scope中的值,以便将它们提供给模板并使用它们。

2个回答

5

简单易学... :-)

var app = angular.module('app', []);
app.controller('myCtrl', function ($scope) {});
app.directive('myDirective', function() {
  return {
    restrict: 'E',
    template: '<p>myDirective:</p>{{firstValue}}, {{secondValue}}, {{thirdValue}}',
    scope: {
      firstValue: '@',
      secondValue: '@',
      thirdValue: '@'
    },
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="myCtrl">
    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
  </div>
</div>

但是下次你真的应该尝试自己编写这种代码... :-)

1

var app = angular.module('app', []);

app.controller('homeCtrl', function ($scope) {


   

});
app.directive('myDirective', function() {

  return {
    restrict: 'AE',
    template: '<h3>My Directive</h3><p>{{firstValue}}|{{secondValue}}|{{thirdValue}}</p>',
    scope: {
      firstValue: '@',
      secondValue: '@',
      thirdValue: '@'
    },

    link: function(scope, element, attr) {

      console.log(scope.firstValue)
      console.log(scope.secondValue)
      console.log(scope.thirdValue)

    }

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">

    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接