从隔离范围指令获取控制器模型 [英] Getting controller model from isolate scope directive
问题描述
我知道这里有 10 亿个关于隔离作用域的问题,但我找不到与这个确切问题直接相关的问题.
I know that there are a billion questions about isolate scope on here, but I could not find one that directly relates to this exact issue.
我的控制器上有一个名为 Model
的属性,所以.. $scope.Model
.然后我有一个需要与模型交互的指令.
I have a property on my controller called Model
, so .. $scope.Model
. I then have a directive that needs to interact with the Model.
我想给指令一个隔离范围,但事实证明这有点困难,因为这样做意味着我不再可以访问模型.我想我可以通过将模型指定为隔离范围内的双向绑定来解决这个问题,就像这样.
I am wanting to give the directive an isolate scope, but this is proving a bit difficult because doing that means I no longer have access to the model. I thought I could solve this by specifying the model as a two-way binding in the isolate scope, like this.
<body ng-app="app" ng-controller="HomeController">
<div custom-directive="Model.Tags"></div>
</body>
javascript
app.directive('customDirective', ['$parse', function($parse) {
return {
restrict: "A",
scope: {
customDirective: "=Model"
},
link: function(scope, element, attributes){
// need to access the controller's "$scope.Model" here for some things.
var model = scope.$eval(attributes.customDirective);
}
}
}])
.controller('HomeController', ['$scope', function($scope) {
$scope.Model = {
Id: "items/1",
Name: "Some Model Object",
Tags: []
};
}]);
我真的不知道为什么这不起作用.根据我看过的所有隔离范围教程,这应该没问题.
I'm really lost as to why this doesn't work. According to all of the isolate scope tutorials I've seen, this should be fine.
将控制器作为参数传递不是一种选择.我需要与之交互的第三方库已经这样做了,显然我不能在同一个 HTML 元素上这样做两次.
Passing the controller as a parameter is not an option. A third party library that I need to interact with already does this, and apparently I can't do that twice on the same HTML element.
推荐答案
您的用法不正确.这将起作用:
Your usage is incorrect. This will work:
<body ng-app="app" ng-controller="HomeController">
<div custom-directive="Model"></div>
</body>
app.directive('customDirective', [function() {
return {
restrict: "A",
scope: {
customDirective: "="
},
link: function(scope, element, attributes){
console.log(scope.customDirective); // this is the $scope.Model due to 2-way binding
}
}
}])
.controller('HomeController', ['$scope', function($scope) {
$scope.Model = {
Id: "items/1",
Name: "Some Model Object",
Tags: []
};
}]);
这篇关于从隔离范围指令获取控制器模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!