AngularJS - 从指令中获取属性值

AngularJS - Getting an attribute value from a directive

好的,所以我有一个指令可以获取属性并读取它(并写出)。

这里是 plunker: http://embed.plnkr.co/IkKPLahPc9yqeHWEQUG3/

我认为这是因为控制器:ctrl inside main-directive.js 什么都没有,而实际操作是发生在隔离指令的控制器 controller.

这里是main-directive.js:

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


app.directive('myCustomer', function() {

  var controller = ['$scope', function($scope) {

    $scope.dan = { 'name': 'Dan', 'nationality': 'ESP' };
    // scope from here obv...

  }];

  var template = 'Getting attribute value of =getInfo... {{getInfo.name}} from {{getInfo.nationality}}';

  return {
    restrict: 'E',
    controller: controller,
    scope: {
      getInfo: "=info"
    },
    template: template
  };
});

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

})

这是我的模板:

<div ng-controller="ctrl">
    <my-customer info="dan">
    </my-customer>
</div>

为什么我的指令没有读取 info 的属性?

按照编码方式,它期望 ctrl 控制器在其范围内有一个名为 "dan" 的 属性。如果您只是传递字符串 'dan',您希望将指令更改为使用 @ 而不是 =

    app.directive('myCustomer', function () {

        var controller = ['$scope', function ($scope) {

            $scope.dan = {'name': 'Dan', 'nationality': 'ESP'};
            // scope from here obv...

        }];

        var template = 'Getting attribute value of =getInfo... {{getInfo.name}} from {{getInfo.nationality}}';

        return {
            restrict: 'E',
            controller: controller,
            scope: {
                getInfo: "@info" //<--NOTE THE CHANGE HERE
            },
            template: template
        };
    });     

你说得对,$scope.dan 对象需要在“ctrl”控制器范围内,并退出隔离指令控制器范围。

app.controller('ctrl', function($scope) {
    $scope.dan = { 'name': 'Dan', 'nationality': 'ESP' };
})

这适用于您为“=info”使用的getInfo设置的双向数据绑定方法