AngularJS1.2 Directive双向绑定属性未反映到View

AngularJS1.2 Directive two Way Binding Attribute is not reflected to View

本文关键字:View 属性 绑定 Directive AngularJS1      更新时间:2024-05-06

我不能在视图中使用scope变量中明显可用的scope属性。

请参阅plnkr:http://plnkr.co/edit/aoRU6YDywA0Q25gKpQGz?p=preview

script.js

// Code goes here
angular.module('myapp', [
  'myapp.directive',
  'myapp.controller'
]);
angular.module('myapp.controller', []).controller('mylist', function($scope) {
  'use strict';
  $scope.mylist = [{
    name: "peter",
    likes: 10
  }, {
    name: "bob",
    likes: 2
  }];
  $scope.testme = 'fdsds';
});
angular.module('myapp.directive', []).directive('pmTable', function factory() {
  var directiveDefinitionObject = {
    scope: {
      data: '=myvar'
    },
    controller: function($scope, $element, $attrs, $transclude) {
      // console.log($scope);
    },
    compile: function compile(tElement, tAttrs, transclude) {
      // Note: The template instance and the link instance may be different objects if the template has been cloned.
      // For this reason it is not safe to do anything other than DOM transformations that apply to all cloned DOM nodes within the compile function.
      // Specifically, DOM listener registration should be done in a linking function rather than in a compile function.
      console.log('inside compile');
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {
          console.log('preLink');
          console.log(scope);
          console.log(scope.data); // available here
          scope.testme = 'testhere';
          // scope.$apply(); // using that one doesn change anything
        },
        post: function postLink(scope, iElement, iAttrs, controller) {
          console.log('postLink');
          console.log(scope);
          console.log(scope.data); // available here
          console.log(scope.testme); // available from the parent scope
          // scope.$apply(); // using that one doesn change anything
        }
      };
    }
  };
  return directiveDefinitionObject;
});

index.html

<!DOCTYPE html>
<html data-ng-app="myapp">
  <head>
    <script data-require="angular.js@1.2.3" data-semver="1.2.3" src="http://code.angularjs.org/1.2.3/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body>
  <div ng-controller="mylist">
    {{mylist|json}}
    {{ testme }}
    <h1>Hello Plunker!</h1>
    <div pm-table myvar="mylist">
        From parent Scope: {{ testme }} <br />
        {{myvar|json}}<br />
        {{data|json}}<br />
        <!-- this following repeat is not working -->
        <tr data-ng-repeat="item in data">
            <td>Name: {{ item.name }}</td>
        </tr>
    </div>
  </div>
  </body>
</html>

pm-table是一个属性。指令的作用域仅限于此属性(或元素),因为您决定使用独立的作用域。CCD_ 2输出来自指令的作用域的值CCD_。

From parent Scope: {{ testme }} <br />将打印控制器范围指定的fdsds。该指令在此不适用。当然,ng-repeat也是如此。data在指令的范围内,此处不适用。

最简单的解决方案是使用scope: true继承作用域。其他任何事情都需要额外的工作。