我无法在视图中使用范围变量中明显可用的范围属性。
请参阅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>
答案 0 :(得分:0)
pm-table
是一个属性。该指令的范围仅限于此属性(或元素),因为您决定使用隔离范围。 console.log(scope.testme);
输出来自指令范围的值testhere
。
From parent Scope: {{ testme }} <br />
将打印fdsds
,由控制器的范围指定。该指令不适用于此处。当然,ng-repeat
也是如此。 data
在指令的范围内,这里不适用。
最简单的解决方案是使用scope: true
的继承范围。其他任何事情都会涉及额外的工作。