所以我有一个指令,在指令视图(html)中,我放了一个控制器,但是它会影响viewModel的其余部分(vm)。将控制器隔离为仅控制特定viewModel的最佳方法是什么?
这就是视图模型和指令的结构,我认为ng-controller="ctrl as vm“只能在"controller”类中找到vm,而不是找到页面上的每一个vm。
指令:
var directive = {
templateUrl: '/Content/app/core/scaffolding/views/popup.html',
restrict: 'A',
link: function (scope, element, attributes) {
console.log('something')
}
};查看:
<div class="directive">
<div class="moreVm">
<a href="" ng-click="vm.goSomewhere" ng-class="{true: 'red'}[vm.someClass]"></a>
</div>
<div class="controller" ng-controller="ctrl as vm">
<a href="" ng-click="vm.click()"></a>
<button ng-click="vm.find()"></button>
</div>
</div>我试着把"ctrl as jvm“写成”ctrl as jvm“,但是仍然是一样的哈哈,这只是一个猜测。
<div class="controller" ng-controller="ctrl as jvm">
<a href="" ng-click="jvm.click()"></a>
<button ng-click="jvm.find()"></button>
</div>发布于 2016-04-08 16:03:56
尝尝这个。
var directive = {
restrict: "A",
scope: true,
bindToController: {},
controller: "ctrl as vm",
templateUrl: "/Content/app/core/scaffolding/views/popup.html"
};发布于 2016-04-08 16:16:06
我给出了一个使用指令的例子,这可能会有一些帮助-- Plunker
如您所见,在directive2中单击该按钮不会在directive1中设置$scope.aValue的值。
JS
var app = angular.module('plunker', [])
.directive("directive1", function accountDir() {
return {
restrict: "EA",
templateUrl: "directive1.html",
scope: {},
controller: function ($scope) {
$scope.$watch("aValue", function(newValue) {
console.log(newValue);
})
}
};
}
)
.directive("directive2", function accountDir() {
return {
restrict: "EA",
templateUrl: "directive2.html",
scope: {},
controller: function ($scope) {
$scope.setAValue = function () {
$scope.aValue = 42;
console.log($scope.aValue);
}
}
};
}
);标记
<body>
<directive1></directive1>
</body>directive1.html
<directive2></directive2>directive2.html
Directive2
<br>
<button ng-click="setAValue()">Set a value</button>发布于 2016-04-08 16:40:16
如果我没猜错,你要不要这样做,当ctrl作为不同的名字,指令console.log不同的值?或者在vm中,但是指令内的值与指令外的值不同?
如果你想先做两个控制器,然后设置不同的值;
controller('ctrl1',function(){ this.name});
controller('ctrl2',function(){ this.name});其他人想要两个
directive('myDir',function(){ return {restrict:'AE',scope:{},controller:function(){this.name='haha'}}})现在,值是isolate with outer
https://stackoverflow.com/questions/36494184
复制相似问题