AngularJS – 设置指令模板中定义的模型
发布时间:2020-12-17 10:26:33 所属栏目:安全 来源:网络整理
导读:我有一个如此定义的指令: angular.module('directives.myInput',[]) .directive('myInput',function($parse,$http,$sce){ return { restrict: 'E',template: 'input type="text" ng-model="searchStr" /',controller: function($scope){ $scope.keyPressed
我有一个如此定义的指令:
angular.module('directives.myInput',[]) .directive('myInput',function($parse,$http,$sce){ return { restrict: 'E',template: '<input type="text" ng-model="searchStr" />',controller: function($scope){ $scope.keyPressed = function(event){ $scope.showDropdown = true; . . . } } }; }); 然后我在html和指令上面有一个按钮,声明如下: <div ng-controller="IndexCtrl"> <button ng-click="startNewLog()">Start</button> <div ng-controller="ItemNewCtrl"> <myInput /> </div> </div> 我想在按钮ng-click上更改/初始化ng-model =“searchStr”模型.我怎样才能做到这一点? 多谢你们,
如果我理解你的话,首先你需要使用$broadcast呼叫子控制器.由于我们不使用隔离范围,我们只需从子控制器调用指令方法:
[简答] 没有隔离范围示例 演示1 Fiddle 对于隔离范围,我会将值映射到自动监听值更改的指令: 隔离范围示例 演示2 Fiddle [完整答案] 没有隔离范围示例 HTML <div ng-controller = "IndexCtrl"> <button ng-click="startNewLog()">Start</button> <div ng-controller="ItemNewCtrl"> <my-input></my-input> </div> </div> JS var app = angular.module('myModule',[]); app.controller('IndexCtrl',function ($scope) { $scope.startNewLog = function(){ $scope.$broadcast('someEvent'); }; }); app.controller('ItemNewCtrl',function ($scope) { $scope.$on('someEvent',function() { $scope.callDirective(); }); }); app.$inject = ['$scope']; app.directive('myInput',function(){ return { restrict: 'E',controller: function($scope){ $scope.searchStr; $scope.keyPressed = function(event){ $scope.showDropdown = true; } },link: function(scope,elm,attrs) { scope.callDirective = function() { scope.searchStr = 'callDirective'; }; } }; }); 隔离范围示例 HTML <div ng-controller = "IndexCtrl"> <button ng-click="startNewLog()">Start</button> <div ng-controller="ItemNewCtrl"> <my-input my-model='contInput'></my-input> </div> </div> JS var app = angular.module('myModule',function ($scope) { $scope.contInput = ''; $scope.count = 0; $scope.$on('someEvent',function() { $scope.contInput = 'hey mate'; }); }); app.$inject = ['$scope']; app.directive('myInput',scope:{searchStr: '=myModel'},controller: function($scope){ $scope.searchStr; $scope.keyPressed = function(event){ $scope.showDropdown = true; } } }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |