Javascript AngularJS1.2指令双向绑定属性未反映到视图中
我不能在视图中使用scope变量中明显可用的scope属性 请参阅plnkr: script.jsJavascript AngularJS1.2指令双向绑定属性未反映到视图中,javascript,angularjs,binding,angularjs-directive,Javascript,Angularjs,Binding,Angularjs Directive,我不能在视图中使用scope变量中明显可用的scope属性 请参阅plnkr: script.js // Code goes here angular.module('myapp', [ 'myapp.directive', 'myapp.controller' ]); angular.module('myapp.controller', []).controller('mylist', function($scope) { 'use strict'; $scope.mylis
// 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表是一个属性。指令的作用域仅限于此属性或元素,因为您决定使用独立的作用域。console.logscope.testme;输出来自指令范围的testhere值
从父作用域:{{testme}}将按照控制器作用域的指定打印fdsds。该指令在这里不适用。当然,对于ng重复也是如此。数据在指令的范围内,此处不适用
最简单的解决方案是继承scope:true的scope。其他任何事情都需要额外的工作