我是AngularJS的新手,对指令性的东西有点困惑。在下面的代码中,我需要使用一个指令创建一个输入字段,该指令位于一个外包模块中,并使用我的自定义指令来关注它。
小心,我不能改变外包模块.
myHtml.html
<body ng-app="main" ng-controller="myCtrl">
<my-field></my-field>
</body>
Outsource.js
var app2 = angular.module('pain', []);
app2.directive('myField', [function() {
return {
scope.f = 'focus-me';
},
template: 'name: <input type="text" class="{{f}}"/>' +
'<br/>' +
'input class is: \"{{f}}\"'
}
}]);
myApp.js
var app1 = angular.module('main', ['pain']);
app1.controller('myCtrl', ['$scope', function($scope) {
$scope.state = true;
}]);
app1.directive('focusMe', ['$timeout', '$parse', function($timeout, $parse) {
return {
restrict: 'C',
link: function(scope, element) {
scope.$watch(scope.state, function() {
console.log('value=', scope.state);
if (scope.state === true) {
$timeout(function() {
element[0].focus();
}, 20);
}
});
}
};
}]);
Fiddle
下面这样的代码是可以的,但是我不能更改外包代码。
It works
发布于 2017-07-22 12:43:18
您必须修复Outsource.js中的代码,以满足您想要做的工作。它有几个问题。请查看我的评论以获得解释:
Outsource.js --就像你的问题中那样
var app2 = angular.module('pain', []);
app2.directive('myField', [function() {
return {
/* directive scope needs to be added as a parameter to the angular directive link function before you can use it. */
scope.f = 'focus-me';
},
// Your template property should be in your return object
template: 'name: <input type="text" class="{{f}}"/>' +
'<br/>' +
'input class is: \"{{f}}\"'
}
}]);
Outsource.js -什么应该是
var app2 = angular.module('pain', []);
app2.directive('myField', function() {
return {
restrict: 'E',
template: 'name: <input type="text" class="{{f}}"/>'+
'<br/>'+
'input class is: \"{{f}}\"',
link: function (scope) {
scope.f='focus-me';
},
controller: [function ($scope) {
// Do Awesome stuff in/with $scope here
}]
};
});
因此,告诉用Outsource.js编写代码的人修复它,否则您无法实现您想要实现的目标。
https://stackoverflow.com/questions/45254197
复制相似问题