2013-12-09 62 views
0

我不能在我的視圖中使用範圍屬性,這在scope變量中是顯而易見的。AngularJS1.2指令雙向綁定屬性不反映到視圖

請參閱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="[email protected]" 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> 

回答

0

pm-table是一個屬性。由於您決定使用隔離範圍,因此該指令的範圍僅限於此屬性(或元素)。 console.log(scope.testme);輸出來自指令範圍的值testhere

From parent Scope: {{ testme }} <br />將打印fdsds,如控制器的範圍所指定。該指令不適用於此。當然,ng-repeat也是如此。 data在指令的範圍內,這裏不適用。

最簡單的解決方案將是一個繼承範圍scope: true。其他任何事情都會涉及額外的工作。