Angular.js将参数传递给指令 [英] Angular.js passing parameter to directive
问题描述
我是Angular的新手,所以如果这个问题的答案很简单,请不要感到惊讶.
I'm a newbie at Angular, so don't be surprise if the answer to this question is pretty basic.
我正在尝试将地图封装在指令中,该地图将具有一些自定义行为:我希望它与服务进行通信,以检索与商家相关的所有点.
I'm trying to encapsulate a map in a directive, the map will have some custom behavior: I want it to communicate with a Service to retrieve all the points related to a merchant.
所以我想将商人作为参数传递给指令:
So I want to pass the merchant as a parameter to the directive:
这是HTML:
<div ng-app="myApp">
<div ng-controller="Ctrl1">
<p>Ctrl 1: {{merchant1}}</p>
<map merchantDetails="{{merchant1}}"></map>
</div>
</div>
这是javascript:
This is the javascript:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl1', function ($scope) {
$scope.merchant1 = "foo"
});
myApp.controller('Ctrl2', function ($scope) {
$scope.merchant2 = "bar"
})
.directive('map', function () {
return {
restrict: 'E',
link: function (scope, element, attrs, controller) {
scope.merchant2 = attrs.merchantDetails;
},
scope: {
merchantDetails: "@"
},
template: 'Ctrl2: {{merchant2}}'
}
});
问题在于模板上的scope.merchant2
从未更新.
我希望它具有"foo",或者最糟的是"bar",而不是空白.
The problem is that scope.merchant2
at the template never gets updated.
I would like it to have "foo", or at worst "bar", not blank.
当我在Chrome中调试此代码时,将永远不会执行控制器Ctrl2
的初始化.为什么?我希望它可以在链接阶段之前完成.
When I debug this in Chrome, controller Ctrl2
initialization is never executed. Why? I would expect it to be done before the link phase.
如何获取传递给Ctrl2
的"foo"值?
How do I do to get the "foo" value passed to Ctrl2
?
可以在此处使用jsfiddle.
The jsfiddle is available here.
推荐答案
您实际上不需要第二个控制器. 我更新了提琴手,请检查它是否是您需要的:
You actually don't need the second controller. I update the fiddler, please check if it's what you need:
https://jsfiddle.net/e7cfcakv/7/
<div ng-app="myApp">
<div ng-controller="Ctrl1">
<p>Ctrl 1: {{merchant1}}</p>
<map merchant-details="{{merchant1}}"></map>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl1', function ($scope) {
$scope.merchant1 = "foo"
});
myApp.directive('map', function () {
return {
restrict: 'E',
link: function (scope, element, attrs, controller) {
scope.merchant2 = scope.merchantDetails;
},
scope: {
merchantDetails: "@"
},
template: 'Ctrl2: {{merchant2}}'
}
});
这篇关于Angular.js将参数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!