这是我的自定义指令代码
(function () {
var app = angular.module('CustDirMod', []);
var custdirCtrl = function ($scope) {
$scope.Person = {
Name: 'Jagan868',
address: {
street: '10 Donwstreet',
city: 'North Avenue',
state: 'Los Angeles'
},
friends: [
'Friend1',
'Friend2',
'Friend3'
]
};
};
var custDirectivewithBinding = function () {
return {
templateUrl: "Friends.html",
restrict: "E",
controller: function ($scope) {
$scope.KnightMe = function (Person) {
Person.rank = "Knight";
}
}
}
};
app.controller('CustDirCtrl', custdirCtrl);
app.directive("custDirectiveBinding", custDirectivewithBinding);
})();
这是我的模板 html
<div class="panel panel-primary">
<div class="panel-heading">
{{ Person.Name }}
</div>
<div class="panel-body">
<div ng-show='!!Person.address'>
<h4>Address :
</h4>
{{Person.address.street}}
<br />
{{Person.address.city}}
<br />
{{Person.address.state}}
</div>
<h4>Friends :</h4>
<br />
<ul>
<li ng-repeat='friend in Person.friends'>
{{friend}}
</li>
</ul>
<div ng-show="!!Person.rank">
Rank : {{Person.rank}}
</div>
<button ng-show="!Person.rank" class="btn btn-success" ng-click="KnightMe(Person)">Knight Me</button>
</div>
</div>
现在是下面的最终 html 页面,我使用上面的自定义指令
<!DOCTYPE html>
<html ng-app="CustDirMod">
<head>
<title>Simple Directives - Angularjs</title>
<script src="Scripts/jquery-3.1.1.js"></script>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/angular-1.5.8.js"></script>
<script src="Scripts/CustomDirective.js"></script>
</head>
<body ng-controller="CustDirCtrl" class="container" style="padding-top:30px;">
<cust-directive-binding></cust-directive-binding><br /><br />
</body>
</html>
现在我尝试在自定义指令中添加隔离范围,如下所示
var custDirectivewithBinding = function () {
return {
templateUrl : "Friends.html",
restrict: "E",
scope: {
userdata: "="
},
controller: function($scope){
$scope.KnightMe = function (Person) {
Person.rank = "Knight";
}
}
}
};
然后在html页面中如下
<body ng-controller="CustDirCtrl" class="container" style="padding-top:30px;">
<cust-directive-binding userdata="Person"></cust-directive-binding><br /><br />
</body>
添加名为“userdata”的隔离范围后,我没有在 UI 中获取任何数据。但如果我从 js 和 html 文件中删除“userdata”隔离范围,它的工作正常。如何解决这个问题。
P.S:我不想将隔离范围本地属性名称命名为与“Person”相同。我只是希望它有所不同,以便我可以轻松区分。
最佳答案
指令中没有范围属性 Person
,您在创建隔离范围时将其重命名为 userdata
。
您需要更改模板以现在使用 userdata
而不是 Person
,或者将 userdata
的名称更改为 Person
这样模板就可以工作
scope: {
userdata: "="
}
// in view
{{ userdata.Name}}
或者
<cust-directive-binding Person="Person">
scope: {
Person: "="
}
// in view
{{ Person.Name}}
关于javascript - 隔离范围不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875622/