简体   繁体   English

简单动态指令AngularJS

[英]Simple Dynamic Directive AngularJS

I have an application that uses an independent directive not tied to the application in anyway but can be called with $scope.$emit() from anywhere. 我有一个使用独立指令的应用程序,该指令无论如何都不会绑定到该应用程序,而是可以在任何地方使用$ scope。$ emit()进行调用。 I would like it to load an internal dynamic template based off of the product id received from the $scope.$on() function in the controller. 我希望它根据从控制器中的$ scope。$ on()函数收到的产品ID加载内部动态模板。

Here is a simplified version of what i have so far ... 这是我到目前为止的简化版本...

index.html index.html

<div quote-application ng-show="ifActive"></div> 

path/to/template.html 路径/到/template.html

<form class="application-modal">
    <button>X</button>

    <!-- this is what i would like to by dynamically loaded -->
    <fieldset product="{{productID}}"></fieldset>

    <button>Add Product</button>
    <button>Cancel</button>
</form>

JS File JS文件

angular.module('client.quote-app', [])

.controller('quoteCtrl', ['$scope', function($scope) {

    $scope.ifActive = false;

    $scope.productID = '0000';

    $scope.$on('requestQuote', function(event, productID) {
        $scope.ifActive = true; 
        $scope.productID = productID; //this is coming through okay
    });

}])

//this loads fine
.directive('quoteApplication', function() {
    return {
        controller  : 'quoteCtrl',
        templateUrl : 'path/to/template.html'
    }
})

//not sure what to do here ...
.directive('product', function() {
    return {
        //<!-- I want this to load a template 
               based off of the productID every 
               time $scope.on() gets called --!>
        templateUrl : 'path/to' + productID + '.html'
    }
})

尝试对templateUrl使用一个函数。

Maybe something like this: 也许是这样的:

 .directive('product', function() { function templatePath(pid) { return 'path/to' + pid + '.html' } return { // I want this to load a template // based off of the productID every // time $scope.on() gets called --!> templateUrl : templatePath(productID) } }) 

index.html - index.html-

<div class="quote-client" quote-application ng-show="state"></div>

app.html - app.html-

<form class="application" ng-submit="">
    <button>X</button>
    <fieldset ng-include="product"></fieldset>
    <button>Add Product</button>
    <button>Cancel</button>
</form>

.js - .js-

angular.module('client.quote-app', [])

.controller('quoteCtrl', ['$scope', function($scope) {

  $scope.state =  false;

  $scope.product = './path/to/' + '0000' + '.html';

  $scope.$on('requestQuote', function(event, product) {
    $scope.product = './path/to/' + product + '.html'; 
    $scope.state = true;
  });

}])

.directive('quoteApplication', function() {
  return {
    controller  : 'quoteCtrl',
    templateUrl : 'path/to/app.html'    
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM