[英]How do I update the view from a different controller in angular.js without using directive?
[英]angular.js - passing an object from directive to the view controller
*请注意:有一个Plunker链接: https ://plnkr.co/edit/PAINmQUHSjgPTkXoYAxf ? p = preview
首先,我想将对象作为指令click事件的参数传递(这对我来说太复杂了),所以我决定通过分别发送事件和对象来简化它。
在我的程序中,对象始终在视图控制器中未定义,而视图本身与Plunker示例相反。
在Plunker示例中,仅在第一个传递事件上才在控制器上对其进行定义(第二个指令click事件可以正常工作)。
的HTML
<pick-er get-obj-d="getObj()" obj-d="obj"></pick-er>
视图控制器
function mainController($scope)
{
$scope.test = "work";
$scope.getObj = function(){
$scope.test = $scope.obj;
}
}
指示:
function PickerDirective()
{
return {
restrict: 'E',
scope: // isolated scope
{
obj : '=objD',
getObj: '&getObjD'
},
controller: DirectiveController,
template:`<div ng-repeat="item in many">
<button ng-click="sendObj()">
Click on me to send Object {{item.num}}
</button>
</div>`
};
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}];
$scope.sendObj = function() {
$scope.obj = {"a":1,"b":2, "c":3};
$scope.getObj();
}
}
}
我的情况下,使用事件会更简单,请看一下以下Plunker:
https://plnkr.co/edit/bFYDfhTqaUo8xhzSz0qH?p=preview
主控制器
function mainController($scope)
{
console.log("mainCTRL ran")
$scope.test = "work";
$scope.$on('newObj', function (event, obj) {
$scope.obj = obj;
$scope.test = obj;
});
}
指令控制器
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}]
$scope.sendObj = function() {
$scope.$emit('newObj', {"a":1,"b":2, "c":3} )
}
}
return {
restrict: 'E',
controller: DirectiveController,
template:'<div ng-repeat="item in many"><button ng-click="sendObj()">Click on me to send Object {{item.num}}</button></div>'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.