Lug*_*aru 4 javascript web angularjs
如何从控制器获取一些数据并在指令中使用它没有问题.但是当我需要从指令中获取数据并在我的控制器中使用它时,我会堆叠这种情况.
例如:
我的控制器:
function MyController($scope, $location, myDirective) {
"use strict";
// here i need use scope.importantValue and create() method from directive
}
Run Code Online (Sandbox Code Playgroud)
我的指示:
.directive("myDirective", function() {
"use strict";
return {
restrict: 'A',
template: '<div></div>',
replace: true,
scope: {
data: '=',
},
link: function(scope, elm) {
scope.importantValue = "value";
function create() {
console.log("Directive works...");
}
};
})
Run Code Online (Sandbox Code Playgroud)
如何在控制器中使用指令中的变量或/和方法?
做到这一点最简单的方法是使这两个控制器和指令获得importantValue,并create()从服务.
angular.module(/* Your module */).service('sharedData', function () {
return {
importantValue: "value",
create: function () {
console.log("Directive works...");
}
};
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以注入sharedData您的指令和控制器,importantValue并create()从任何一个地方访问.
| 归档时间: |
|
| 查看次数: |
2805 次 |
| 最近记录: |