如何在隔离范围内检索自定义 属性?

How to retrieve custom property in isolate scope?

我已经阅读了很多关于如何在隔离范围内进行绑定但没有阅读如何在模板中检索范围自定义属性的示例。

我认为修复一定很简单,但我就是不明白这里出了什么问题

<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body>
  <div my-directive>

  </div>

  <script>
    angular.module('myApp', [])
    .directive('myDirective', function() {
      return {
        restrict: 'A',
        scope: {
            data.myProperty:"1234"
        },
        template:'Inside myDirective, isolate scope: {{ data.myProperty }}'
      };
    })
  </script>

</body>
</html>

不知为何,无法联系到 data.myProperty。

您不能像以前那样直接使用和访问绑定中的有界属性 data.myProperty:"1234"。它最终会导致错误。

您必须通过指令的 attribute 传递自定义 属性。在这里你可以考虑添加 custom-data 属性,在它上面添加提及范围 属性 名称。所以它会被传递给独立的范围指令。

控制器

$scope.data = {
   myProperty: 'My Property Value'
}

Html

<div my-directive custom-data="data">

</div>

指令

angular.module('myApp', [])
.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
        customData: '=data'
        //without alias it will look like below.
        //customData: '='
    },
    template:'Inside myDirective, isolate scope: {{ data.myProperty }}'
    //without alias template would look like below
    //template:'Inside myDirective, isolate scope: {{ customData.myProperty }}'
  };
})

Note: It seems like you are using older unstable version. If possible update angular to latest angularjs 1.7.x version, to find more features and performant angularjs. After 1.5.x version, you could also use < inside binding (customData: '<data') to keep one way data binding flow. Just to not confuse you I used =(two way data binding) for demo.